在
Swift 4中,许多基金会团队已经讨论过与Swift 3相比,使用keyPaths要容易得多.这引出了一个问题……什么是keyPath?说真的,我找不到任何明确的资源.
Objective-C能够动态而不是直接引用属性.这些引用称为keypaths.它们与直接属性访问不同,因为它们实际上不读取或写入值,它们只是将其存放以供使用.
原文链接:https://www.f2er.com/swift/319513.html让我们定义一个名为Cavaliers的结构和一个名为Player的结构,然后创建每个结构的一个实例:
// an example struct struct Player { var name: String var rank: String } // another example struct,this time with a method struct Cavaliers { var name: String var maxPoint: Double var captain: Player func goTomaxPoint() { print("\(name) is now travelling at warp \(maxPoint)") } } // create instances of those two structs let james = Player(name: "Lebron",rank: "Captain") let irving = Cavaliers(name: "Kyrie",maxPoint: 9.975,captain: james) // grab a reference to the `goTomaxPoint()` method let score = irving.goTomaxPoint // call that reference score()
最后一行创建了一个名为score的goTomaxPoint()方法的引用.问题是,我们不能创建对队长名称属性的引用,但keypath可以做.
let nameKeyPath = \Cavaliers.name let maxPointKeyPath = \Cavaliers.maxPoint let captainName = \Cavaliers.captain.name let cavaliersName = irving[keyPath: nameKeyPath] let cavaliersMaxPoint = irving[keyPath: maxPointKeyPath] let cavaliersNameCaptain = irving[keyPath: captainName]
请使用Xcode 9或功能快照进行测试.