[swift-evolution] [Pitch] Property reflection
Ricardo Parada
rparada at mac.com
Fri May 27 13:53:06 CDT 2016
> On May 26, 2016, at 9:25 PM, Austin Zheng via swift-evolution <swift-evolution at swift.org> wrote:
>
> ```
> myPerson.typedReadWriteProperty<Int>("age")?.set(30)
>
> try myPerson.allNamedProperties["age"]?.set(30)
> ```
>
Can you elaborate on what this API would be used for? KVC? For instance, I played with Mirror the other day and my code to get a value given the property name looked more like this:
let age = myPerson.value(forKey:”age”) as! Int
And this is what I did:
// KVC stands for key-value-coding… but I only know how to get values. I don’t know how to set values
protocol KVC {
func value(forKey key: String) -> Any!
}
// Default implementation
extension KVC {
func value(forKey key: String) -> Any! {
let aMirror = Mirror(reflecting:self)
for case let (label?, value) in aMirror.children {
if label == key {
return value
}
}
return nil
}
}
public struct Person : KVC {
let firstName: String
let lastName: String
let age: Int
func fullName() -> String {
return "\(firstName) \(lastName)"
}
}
let aPerson = Person(firstName:"John", lastName:"Doe", age:48)
// It works for stored properties
let lastName = aPerson.value(forKey:"lastName") as! String
print("Last name is \(lastName)")
// It does not work for instance methods, i.e. fullName is not a stored property
let fullName = aPerson.value(forKey:"fullName")
if fullName != nil {
print("Full name is \(fullName)")
} else {
print("Unable to get fullName via KVC")
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160527/6fdd9ed7/attachment.html>
More information about the swift-evolution
mailing list