这是我的代码的一部分:
if let newValue = change?[NSKeyValueChangeNewKey] {
print("\(newValue)")
faceBounds = newValue as? CGRect
print("\(faceBounds)" + " in controller")
dispatch_async(dispatch_get_main_queue(),{ () -> Void in self.updateFaceRectView()})
}
其中“faceBounds”是CGRect?类型。
但是,这是我得到的系统的输出:
NSRect: {{116.24999, 337.49997}, {86.249992, 86.249992}}
nil in controller
发生了什么事?为什么“faceBounds”没有获得正确的值?
<小时/>[更新]
也尝试过这个,
if let newValue = change?[NSKeyValueChangeNewKey] {
var str: String?
str = newValue as? String
print("\(str)")
// Still prints nil
}
我对使用转换的了解是否错误?
顺便说一句,如果有人想知道,newValue 是一个 AnyObject 类型。
最佳答案
如 documentation 中所写:
AnyObject can represent an instance of any class type.
NSRect(和 CGRect)是结构类型而不是类类型,因此它们与 AnyObject
不兼容,所以newValue as? CGRect
行不通的。您可以尝试将类型转换转换为 Any
首先,然后尝试向下转型为 CGRect
.
let newValue = change?[NSKeyValueChangeNewKey] as! Any
faceBounds = newValue as? CGRect
关于swift - Swift 中的转换未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33472249/