ios - Swift 将键路径作为函数的参数传递

标签 ios swift nspredicate swift-keypath

我需要能够将#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/

相关文章:

swift - 如何调整UITextField.leftView的大小?

ios - 搜索 NSDictionary 对象的 NSArray

ios - Facebook。如何获取我的应用程序的所有用户列表?

ios - Xcode Storyboard中实用程序 Pane 中的 adjustsFontSizeToFitWidth

ios - 如何正确更新AUSampler的loadInstrument属性?

swift - stack view自动更新时调用了哪些方法

ios - UICollectionView 单元格未添加为 UICollectionView 的 subview

ios - Swift - 将 pickerView 添加到 UIViewController 中的文本字段

ios - NSDictionary 的 NSArray 上的 NSPredicate

ios - 使用 NSPredicate 在类似于 SQL WHERE IN 子句的 NSArray 中查找元素