Skip to content

0x052-Swift-keyPath示例

swift
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
    func access<Value>(keyPath: KeyPath<Person, Value>) -> Value {
        return self[keyPath: keyPath]
    }
}

let person = Person(name: "xiao")
let result = person.access(keyPath: \.name)
class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
    func access<Value>(keyPath: KeyPath<Person, Value>) -> Value {
        return self[keyPath: keyPath]
    }
}

let person = Person(name: "xiao")
let result = person.access(keyPath: \.name)

非常有用的可以使用keypath来替代闭包

swift
let peoples: [People] = []
// 传统方式
let names1 = peoples.map { $0.name }
// 基于 KeyPath 的方式
let names2 = peoples.map(\.name)
let peoples: [People] = []
// 传统方式
let names1 = peoples.map { $0.name }
// 基于 KeyPath 的方式
let names2 = peoples.map(\.name)

非常好的总结文档参考:
https://fatbobman.com/zh/posts/comprehensive-guide-to-mastering-keypath-in-swift/