问题
for a unit test of mine, I wrote a small helper that can get me a property Value by name.
let m = Mirror(reflecting: self)
let child1 = m.descendant(name)
now the problem is that the child has Type Any? but the properties real type is e.g. Bool? So Any is actually an Optional!
Thats why if child1 is Bool?
never fires because Any? isn't the Bool?.
But child1! is Bool?
doesn't compile.
And child1! is Bool
isn't true!
So how do I 'unbox' this reflected Any? value?
a small example of what I mean
import UIKit
class ViewController: UIViewController {
let name = "asd"
let boolvalue: Bool = true
var optboolvalue: Bool? = true
override func viewDidLoad() {
print( getNumberForBool("boolvalue") )
print( getNumberForBool("optboolvalue") )
}
func getNumberForBool( name: String ) -> NSNumber {
let m = Mirror(reflecting: self)
let child1 = m.descendant(name)
if(child1 != nil) {
//! only works for bool, not for bool?
if let b = child1 as? Bool {
return NSNumber(bool: b)
}
//this would be my interpretation of how to do it ... unwrap the any and unwrap it again. this doesn't compile though :)
// if let b = child1! as! Bool? {
// return NSNumber(bool: b!)
// }
}
return NSNumber(bool: false)
}
}
NOTE
The type of child1 for the case Bool?:
▿ Optional(Optional(true)) ▿ Some : Optional(true) - Some : true
回答1:
solution
I worked around the issue of not being able to cast an to Bool? by using reflection again
if let any = child1, let maybeB = Mirror(reflecting: any).descendant("Some") as? Bool {
if let b = (maybeB as Bool?) {
return NSNumber(bool: b)
}
}
reflection ^ 2 :D
the complete gist:
https://gist.github.com/Daij-Djan/18e8ab9bcbaa3f073523
回答2:
the ??
operator unwraps the optional in case there is Some
inside. If there is not, the value that is passed after eg. let foo = someOptional ?? alternativeValue
.
This would give you an unwrapped Any
. Since Swift is strongly typed you will only be getting the Bool if you would cast.
if let b = child, let c = b as? Bool {
return NSNumber(bool: c)
}
来源:https://stackoverflow.com/questions/33707460/swift2-reflection-help-convert-the-value-i-get-type-any-to-bool-or-bool-acc