[swift-evolution] [Pitch] Property reflection

Ricardo Parada rparada at mac.com
Fri May 27 15:30:16 CDT 2016


Would it let me get a property if it does not correspond to a property, or computed property? 

For example, would I be able to get the value returned by a fullName() instance method that concatenates the firstName and lastName properties together and returns the result? Or would it only work if fullName were implemented as a computed property as opposed to an instance method? 

Thanks



> On May 27, 2016, at 2:59 PM, Austin Zheng <austinzheng at gmail.com> wrote:
> 
> 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 <rparada at mac.com> wrote:
>> 
>>> 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/11c118ef/attachment.html>


More information about the swift-evolution mailing list