Nate Albright
Nate Albright

Reputation: 13

If else statement to define an NSPredicate

I am trying to define a predicate based on a segment controller switch.

if self.streamtype == "case1" {
    let predicatearray = defaults.object(forKey: "case1") as! [String]
    let predicate = NSPredicate(format: "UserID IN %@" , predicatearray)
} else if self.streamtype == "case2" {
    let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
} else {
    let predicatearray = defaults.object(forKey: "case3") as! [String]
    let predicate = NSPredicate(format: "UserID IN %@", predicatearray)
}

let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "Post", predicate: predicate)

I am getting an error saying:

"Cannot be sent to an abstract object of class NSPredicate: Create a concrete instance!"

Also, it is telling me that the initialization of the predicate variable was never used. I've tried writing the function a couple of different ways but this made the most sense to me since I need to update the predicate only when loading new info so I just put both functions into one.

Upvotes: 0

Views: 487

Answers (1)

Eugene Dudnyk
Eugene Dudnyk

Reputation: 6030

You are defining predicate inside of if {} or else {} scope, that's why it is not visible outside of the scope.

var predicate : NSPredicate!
if self.streamtype == "case1" {
    let predicatearray = defaults.object(forKey: "case1") as! [String]
    predicate = NSPredicate(format: "UserID IN %@", predicatearray)
} else if self.streamtype == "case2" {
    predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
} else {
    let predicatearray = defaults.object(forKey: "case3") as! [String]
    predicate = NSPredicate(format: "UserID IN %@", predicatearray)
}

let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "Post", predicate: predicate)

Upvotes: 2

Related Questions