我需要能够将#keypath 传递给函数来过滤我的 CoreData 记录。
我是这样做的:
func filteredExercises(with propertyKeyPath: #keyPath, filter: Any) {
do {
let filteredExercises = try CoreStore.fetchAll(
From<ExerciseEntity>(),
Where<ExerciseEntity>("%K = %@", #keyPath(ExerciseEntity.muscle.name), filter)
)
} catch {
}
}
但肯定#keyPath 不是一个类型,如何正确地做呢?或者我是否需要准备一个过滤字符串,我将像谓词一样传递给 func?
最佳答案
如果您想使用#keyPath
,那么它只是一个字符串。
(创建旨在与 KVC 一起使用的字符串的一种更安全的形式。)
声明参数类型为String
,其中要接收#keyPath
,传给任何接受#keyPath
的地方。
func filteredExercises(with propertyKeyPath: String, filter: Any) {
do {
let filteredExercises = try CoreStore.fetchAll(
From<ExerciseEntity>(),
Where<ExerciseEntity>("%K = %@", propertyKeyPath, filter)
)
} catch {
}
}
如果您需要使用 Swift 原生 KeyPath
,那是另一个问题。
关于ios - Swift 将键路径作为函数的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55904135/