美文网首页
swift 键路径

swift 键路径

作者: gaookey | 来源:发表于2020-08-25 11:21 被阅读0次
    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 进阶。”

    相关文章

      网友评论

          本文标题:swift 键路径

          本文链接:https://www.haomeiwen.com/subject/qliajktx.html