I have the following question about swift, let say I have an class like so:
class Person {
var firstName, lastName, eyeColor: String
init(firstName: String = "", lastName: String = "", eyeColor: String = "") {
self.firstName = firstName
self.lastName = lastName
self.eyeColor = eyeColor
}
}
I could for example create a person like so:
var myFriend = Person(firstName: "Robin", eyeColor: "Yellow")
However as you can tell now I have not assigned a value to lastName aka this will be empty or "".
What I want to do is iterate over all values in myFriend and check if one is empty, if thats true I would like it to replace the empty value with something like "No information".
I did find something like
let mirroredRecord = Mirror(reflecting: myFriend)
for (index, attr) in mirroredRecord.children.enumerated() {
if var value = attr.label as String? {
if value == "" {
value = "No info"
}
print("Attr \(index): \(value) = \(attr.value)")
}
}
However that does not change the value in the myFriend variable.
In my head the following seems logical but i'm unsure how to perform this action in swift.
for (index, attr) in mirroredRecord.children.enumerated() {
if var value = attr.label as String? {
if value == "" {
myFriend.value = "No info"
}
print("Attr \(index): \(value) = \(attr.value)")
}
}
However because .value is not one of the options (firstName, lastName, eyeColor) it doesn't like it.
Does anyone have any options or solutions regarding this?
"No Information"as default value?init(firstName: String = "No Information", lastName: String = "No Information", eyeColor: String = "No Information") {StringandMirror. This is precisely what optionals are for.