Reputation: 1
I am using Mirror to access the children of my struct like this:
struct TestType {
var firstName: String
var lastName: String
var value: String {
return firstName + lastName
}
}
use case:
let person: TestType = TestType(firstName: "Tim", lastName: "Cook")
for property in Mirror(reflecting: person).children {
print("label: \(property.label!)", "value: \(property.value)")
}
results:
label: firstName value: Tim
label: lastName value: Cook
Now my goal is do the same thing for the person
constant as well, with that said, I want be able to access the label of person
which is person and the value of it, the result should look like this:
label: person value: Tim Cook
How can i do this in Swift?
Upvotes: 0
Views: 111
Reputation: 123
Honestly I have no idea why need to use Mirror here) would be great if you would describe it in as a comment below this answer. I would appreciate it)
but the reason why you can't what you need is because of Mirror
can't see computed properties, as far as I know. Any way you can customise your init method to reach what you need. But remember that using Mirror
is too expensive, for example: if it in inherited object it will parse every single thing in parent classes which could be accessible for Mirror
struct TestType {
let firstName: String
let lastName: String
let person: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
person = [firstName, lastName].joined(separator: " ")
}
}
Upvotes: 0