How to write a BOOL predicate in Core Data?
Swift 3
let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))
In Swift 3 you should use NSNumber(value: true)
.
Using NSNumber(booleanLiteral: true)
and in general any literal initialiser directly is discouraged and for example SwiftLint (v. 0.16.1) will generate warning for usage ExpressibleBy...Literal
initialiser directly:
Compiler Protocol Init Violation: The initializers declared in compiler protocols such as
ExpressibleByArrayLiteral
shouldn't be called directly. (compiler_protocol_init)
Swift 4.0
let predicate = NSPredicate(format: "boolAttribute == %@", NSNumber(value: true))
From Predicate Programming Guide:
You specify and test for equality of Boolean values as illustrated in the following examples:
NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"anAttribute == %@", [NSNumber numberWithBool:aBool]];
NSPredicate *testForTrue = [NSPredicate predicateWithFormat:@"anAttribute == YES"];
You can also check out the Predicate Format String Syntax.
Don't convert to NSNumber, nor use double "=="
More appropriate for Swift >= 4:
NSPredicate(format: "boolAttribute = %d", true)
Note: "true" in this example is a Bool (a Struct)