I'm trying to use swift reflection to manage changes to properties of various classes. In testing with a playground, I put together the following code:
class myClass
{
var fieldOne:String?
var fieldTwo:Int?
var fieldThree:Float?
}
var oneMyClass = myClass()
oneMyClass.fieldOne = "blah"
let aMirror = Mirror(reflecting: oneMyClass)
for thing in aMirror.children
{
print(thing.label!)
print(thing.value)
}
This results in the following output:
fieldOne
Optional("blah")
fieldTwo
nil
fieldThree
nil
The property names are great but I don't want the Optional, I just want the value so, of course, I unbox it by using:
print(thing.value!)
Except that returns the following error:
Playground execution failed: /var/folders/blahblahblah...swift:21:22: error:
cannot force unwrap value of non-optional type 'Any' (aka 'protocol<>')
print(thing.value!)
~~~~~~~~~~~^
when it hits the nil values.
BUT, if you try to compare thing.value to nil, it tells you that an Any type cannot BE nil so you're not allowed to make that comparison.
Any ideas on what I can do, however convoluted, to get either just the value itself or the nil?
Aucun commentaire:
Enregistrer un commentaire