iosswiftnspredicateswift-keypath

Swift passing key path as a param of func


I need to be able to pass #keypath to a func to filter my CoreData records.

I do smth like this:

func filteredExercises(with propertyKeyPath: #keyPath, filter: Any) {

        do {
            let filteredExercises = try CoreStore.fetchAll(
                From<ExerciseEntity>(),
                Where<ExerciseEntity>("%K = %@", #keyPath(ExerciseEntity.muscle.name), filter)
            )

        } catch {

        }
    }

But for sure #keyPath is not a type, how to do it correctly? Or Do I need to prepare a filtered string which I will pass to a func like a predicate?


Solution

  • If you want to work with #keyPath, then it's just a String. (A little safer form of creating a String intended to work with KVC.)

    Declare the parameter type as String, where you want to receive #keyPath, and pass it to anywhere #keyPath is accepted.

    func filteredExercises(with propertyKeyPath: String, filter: Any) {
    
        do {
            let filteredExercises = try CoreStore.fetchAll(
                From<ExerciseEntity>(),
                Where<ExerciseEntity>("%K = %@", propertyKeyPath, filter)
            )
    
        } catch {
    
        }
    }
    

    If you need to work with Swift-native KeyPath, that's another issue.