Search code examples
ioscore-dataswiftnscompoundpredicatexcode6.1

NSCompoundPredicate error in Xcode 6.1


Back in Xcode 6, in a project using Core Data I had the following line. It worked fine.

fetchRequest.predicate = NSCompoundPredicate(type: .AndPredicateType, subpredicates: [predicate, datePredicate])

predicate and datePredicate are of NSPredicate type.

Yesterday I updated to Xcode 6.1 and now this above line gives this error Could not find member 'AndPredicateType'. Specifying the entire value like this NSCompoundPredicateType.AndPredicateType didn't work either.

Then I changed the line to use its convenience method line below.

fetchRequest.predicate = NSCompoundPredicate.andPredicateWithSubpredicates([predicate, datePredicate])

Now I get a new error Cannot convert the expression's type '()' to type 'NSPredicate?'. I don't understand why. The documentation doesn't show any deprecations or changes to NSCompoundPredicate either.

Can anyone please tell me how to correct this?

Thank you.


Solution

  • The initializer

    extension NSPredicate {
        convenience init?(format predicateFormat: String, _ args: CVarArgType...)
    }
    

    is a failable initializer now. It returns an optional NSPredicate? and you have to unwrap the result (or use optional binding). For example:

    let compoundPredicate = NSCompoundPredicate(type: .AndPredicateType, subpredicates: [predicate!, datePredicate!])
    // Or:
    let compoundPredicate = NSCompoundPredicate.andPredicateWithSubpredicates([predicate!, datePredicate!])
    

    References: