ImanX
ImanX

Reputation: 816

How to change value a variable by Mirror?

There is a class that this has fields inside it, I wanna by Swift Reflection to name Mirror get all fields and change with new value, I can get all child of class name and value

let m = Mirror(reflecting: self)
   for item in m.children {
       print("\(item.name) \(item.value)")
}

but not to be change value of variable:

let m = Mirror(reflecting: self)
   for item in m.children {
       item.value = "new Value"
}

and give a error because field is immutable:

Cannot assign to property: 'item' is a 'let' constant

is there a way for change value by Mirror is Swift?

While Java has ability for this job by Reflection

UPDATE

I use var in loop and can change value but field of value not changed in class.

let m = Mirror(reflecting: self)
   for var item in m.children {
    item.value = "new Value"
}

Upvotes: 4

Views: 1953

Answers (2)

DavidWeldon
DavidWeldon

Reputation: 121

This looks like a solution, although I'm yet to use it: Swift Runtime Library

Upvotes: 2

Ali Ihsan URAL
Ali Ihsan URAL

Reputation: 1974

I found a solution. I think it helps to you

func toJSON() throws -> Any? {
    let mirror = Mirror(reflecting: self)

    guard !mirror.children.isEmpty else { return self }

    var result: [String: Any] = [:]

    for child in mirror.children {
        if let value = child.value as? JSONSerializable {
            if let key = child.label {
                result[key] = try value.toJSON()
            } else {
                throw CouldNotSerializeError.undefinedKey(source: self, type: String(describing: type(of: child.value)))
            }
        } else {
            throw CouldNotSerializeError.noImplementation(source: self, type: String(describing: type(of: child.value)))
        }
    }

    return result
}

Upvotes: 2

Related Questions