Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Dynamically generate NSPredicate?

I'm trying to dynamically create predicates and perform a fetch.

Values can either be String or Int, when and int value is sent to NSPredicate initializer it crashes with the following error:

-[__NSCFNumber rangeOfString:]: unrecognized selector sent to instance

I know the problem is %@ format for Int, but is there a way to make this dynamic so that I don't have to manually check for String and Int and then create the predicate?

var keyValues: [String: AnyObject]
var predicates: [NSPredicate]()

for (key, value) in keyValues {
   var predicate = NSPredicate(format: "%K = %@", key: [value])
   predicates.append(predicate) 
}

var compundPredicate = NSCompoundPredicate.andPredicateWithSubpredicates(predicates)
like image 263
aryaxt Avatar asked Dec 01 '22 15:12

aryaxt


1 Answers

value as NSObject does the trick:

var keyValues: [String: AnyObject] = ["name" : "John Doe", "age" : 39]
var predicates = [NSPredicate]()

for (key, value) in keyValues {
    var predicate = NSPredicate(format: "%K = %@", key, value as NSObject)
    predicates.append(predicate) 
}

var compundPredicate = NSCompoundPredicate.andPredicateWithSubpredicates(predicates)
println(compundPredicate)

Output:

name == "John Doe" AND age == 39

Update for Swift 3/4:

let keyValues = ["name" : "John Doe" as NSObject, "age" : 39 as NSObject]
var predicates = [NSPredicate]()

for (key, value) in keyValues {
    let predicate = NSPredicate(format: "%K = %@", key, value)
    predicates.append(predicate)
}

let compundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)

Or shorter:

let keyValues = ["name" : "John Doe" as NSObject, "age" : 39 as NSObject]
let predicates = keyValues.map { NSPredicate(format: "%K = %@", $0.key, $0.value) }
let compundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
like image 179
Martin R Avatar answered Dec 17 '22 00:12

Martin R