Reputation: 33
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!
Upvotes: 3
Views: 2801
Reputation: 1538
Unfortunately, you cannot modify value with built-in Mirror
.
Maybe try Runtime named library instead (which's the successor of now deprecated Reflection library).
OR
You can make it without reflection if it is acceptable for you, like:
class MyObject: NSObject {
@objc public var myString : String = "Not working"
}
func test() {
let value = "It works!"
let member = "myString"
let myObject = MyObject()
myObject.setValue(value, forKey: member)
print("New value: \(myObject.myString)")
}
Hope it helps you.
Upvotes: 3
Reputation: 71854
Swift's reflection capabilities are based around a
struct
calledMirror
. You create a mirror for a particularsubject
and the mirror will then let you query it.
Means with Mirror
you can not modify the subject
in your case MyObject
.
Read HERE for more info.
EDIT:
You can simply update your class property as shown below:
func test() {
let myObject = MyObject()
myObject.myString = "It works!"
print("New value: \(myObject.myString)") // "New value: It works!"
}
Upvotes: 0