WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Day 59 challenge

Forums > 100 Days of SwiftUI

In the first part of the challenge for day 59, I thought %K would be an appropriate substitution for BEGINSWITH, but when I build the project, I see Thread 1: "Unable to parse the format string \"%K %K %@\"". In the solution, I see Paul goes with string interpolation. I suppose I can see why that works, but I'm not sure why the variable replacement option doesn't.

I also then wondered, since string interpolation works, couldn't it also be used in place of the other replaced strings (since it has a less alien syntax) e.g. NSPredicate(format: "\(filterKey) \(type) %@", filterValue). It seems to work – is one way preferable to another for any reason?

Thanks

   

%K is an argument substitution for indicating a keypath. BEGINSWITH is not a keypath on whatever object you are supplying to the NSPredicate but rather is the operator of the predicate.

So if you have something like this:

@objcMembers
class Person: NSObject {
   let firstName: String
   let lastName: String
   let age: Int

   //other stuff like init, etc...
}

You can build an NSPredicate like so:

let ageIs33Predicate = NSPredicate(format: "%K == %i", #keyPath(Person.age), 33)

which is the equivalent of:

let pred = NSPredicate(format: "age = %i", 33)

There is no subtitution code for an operator like BEGINSWITH so you have to use string interpolation like Paul does in the solution if you want that part to be dynamic.

1      

Thanks @roosterboy, I think I get it. And I guess I must have been mistaken about string interpolation working for filterValue

   

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.