Yes, it was pretty much meant as a KVC-like feature for Swift. Get a reference to a property from a string which would allow you to get and set its value.
On Fri, May 27, 2016 at 11:53 AM, Ricardo Parada <[email protected]> wrote: > > On May 26, 2016, at 9:25 PM, Austin Zheng via swift-evolution < > [email protected]> 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") > } > > > >
_______________________________________________ swift-evolution mailing list [email protected] https://lists.swift.org/mailman/listinfo/swift-evolution
