UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

1      

%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.

2      

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

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.