Getting string from Swift 4 new key path syntax?

前端 未结 4 1952
别那么骄傲
别那么骄傲 2021-02-01 14:33

How can you get a string value from Swift 4 smart keypaths syntax (e.g., \\Foo.bar)? At this point I\'m curious about any way at all, does not matter if it

4条回答
  •  遥遥无期
    2021-02-01 14:53

    Expanding on @Andy Heard's answer we could extend KeyPath to have a computed property, like this:

    extension KeyPath where Root: NSObject {
        var stringValue: String {
            NSExpression(forKeyPath: self).keyPath
        }
    }
    
    // Usage
    let stringValue = (\Foo.bar).stringValue
    print(stringValue) // prints "bar"
    
    

提交回复
热议问题