lundi 25 février 2019

How to set a member variable value using reflection in Swift?

I've read through numerous tutorials and tried countless things to get this to work but can't seem to find a solution.

All I want to do is use reflection to set the value for a named member variable. I can read the values just fine, but how do I write a value?

Here is my sample code:

class MyObject
{
    public var myString : String = "Not working"
}

func test()
{
    let value = "It works!"
    let member = "myString"
    var myObject = MyObject()

    let mirror = Mirror(reflecting: myObject)
    for (_, var attr) in mirror.children.enumerated() {
        if attr.label == member {
            print("Setting value of \(member)")

            // attempt to set the member variable value
            attr.value = value

            break
        }
    }

    print("New value: \(myObject.myString)")
}

Running this example, the output prints the old value of myString. I'm using Swift 4 for iOS.

Any help would be appreciated. Thank you!





Aucun commentaire:

Enregistrer un commentaire