问题描述
对于我的单元测试,我写了一个小帮手,可以通过名称获得属性Value.
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)
现在的问题是孩子的孩子有Any Type吗?但属性的实类型是例如布尔?因此,Any实际上是可选的!
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!
这就是为什么if child1 is Bool?
永远不会因为任何原因而触发的原因?不是布尔吗?
但是child1! is Bool?
无法编译.
而且child1! is Bool
是不正确的!
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?
我的意思的一个小例子
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)
}
}
注意
案例Bool的child1的类型?:
The type of child1 for the case Bool?:
▿可选(可选(true)) ▿一些:选填(true) -有些:是的
▿ Optional(Optional(true)) ▿ Some : Optional(true) - Some : true
推荐答案
解决方案
我解决了无法向Bool投影片的问题?再次使用反射
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)
}
}
反射^ 2:D
https://gist.github.com/Daij-Djan/18e8ab9bcbaa3f073523
这篇关于Swift2反射帮助.将我得到的值(键入Any?)转换为Bool或Bool?因此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!