struct Address {
var street: String
var city: String
var zipCode: Int
}
struct Person {
let name: String
var address: Address
}
let streetKeyPath = \Person.address.street // Swift.WritableKeyPath<Person, Swift.String>
let nameKeyPath = \Person.name // Swift.KeyPath<Person, Swift.String>
let simpsonResidence = Address(street: "1094 Evergreen Terrace",
city: "Springfield", zipCode: 97475)
var lisa = Person(name: "Lisa Simpson", address: simpsonResidence)
lisa[keyPath: nameKeyPath] // Lisa Simpson
lisa[keyPath: streetKeyPath] = "742 Evergreen Terrace"
var bart = Person(name: "Bart Simpson", address: simpsonResidence)
let people = [lisa, bart]
people[keyPath: \.[1].name] // Bart Simpson
// 等效于 "Hello".count
"Hello"[keyPath: \.count]
摘录来自: Chris Eidhof. “Swift 进阶。”
网友评论