1

After the Xcode 9.3 update, I've noticed that if you want to have Predicate like this:

let predicate = NSPredicate(format: "preferred = %@", true as CVarArg)

You have a crash. But in Xcode 9.2 this wasn't a problem. Any idea?

Alessandro Francucci
  • 1,528
  • 17
  • 25

3 Answers3

8

// Solution 3 [ Apple Documentation ]

let predicate = NSPredicate(format: "preferred == TRUE")

The exception occurs because true is not an object (%@). You need the %d placeholder

let predicate = NSPredicate(format: "preferred = %d", true)
vadian
  • 274,689
  • 30
  • 353
  • 361
0

After a bit of investigation, I've discovered how to fix this. In short:

// Solution 1 [ NSNumber ]
let bool = NSNumber(booleanLiteral: true)
let predicate = NSPredicate(format: "preferred = %@", bool as CVarArg)

// Solution 2 [ Bool ] (static example)
let predicate = NSPredicate(format: "preferred == YES")

As also explained here, it's simply better to deal with Obj-C type instead of Swift type when we have to deal with this kind of methods.

Alessandro Francucci
  • 1,528
  • 17
  • 25
0

I think you can also use this:

NSPredicate(format: "preferred = true")
  • Yep, it's also a solution! I also noticed that. Basically it's just better to avoid to pass swift boolean as CVarArg like I did at first. Can't understand exactly why, but nevermind. – Alessandro Francucci May 17 '18 at 10:39