What is KeyPath used for?

In Swift 4, many of the Foundation team discussed how much easier it is to use keyPaths compared to Swift 3. This begs the question ... What is keyPath? Seriously, I cannot find any clear resources.

+4
source share
1 answer

Objective-C has the ability to refer to a property dynamically, and not directly. These links are called key. They differ from direct access to properties because they actually do not read or write the value, they just hid it for use.

Define a structure called Cavaliers and a structure called Player, then create one instance of each of them:

// 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()

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]

, Xcode9 .

+8

Source: https://habr.com/ru/post/1678827/


All Articles