以下是 Swift 中使用 Key Path 的代码示范:
// 定义一个 Person 类
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
// 创建一个 Person 实例
let person = Person(name: "Tom", age: 20)
// 定义一个 Key Path
let nameKeyPath = \Person.name
// 通过 Key Path 获取属性值
let personName = person[keyPath: nameKeyPath]
print(personName) // 输出 "Tom"
// 修改属性值
person[keyPath: nameKeyPath] = "Jack"
print(person.name) // 输出 "Jack"
// 定义一个只读的 Key Path
let ageKeyPath = \Person.age
let personAge = person[keyPath: ageKeyPath]
print(personAge) // 输出 20
// 使用 Key Path 作为函数参数
func printPropertyValue(from object: T, with keyPath: KeyPath<T, String>) {
let propertyValue = object[keyPath: keyPath]
print(propertyValue)
}
printPropertyValue(from: person, with: nameKeyPath) // 输出 "Jack"