在 Swift 中的转换没有按预期工作

Casting in Swift not working as expected

这是我的代码的一部分:

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)是结构类型而不是 class 类型,因此它们与 AnyObject 不兼容,因此 newValue as? CGRect 将不起作用。您可以先尝试转换为 Any,然后再尝试向下转换为 CGRect.

let newValue = change?[NSKeyValueChangeNewKey] as! Any
faceBounds = newValue as? CGRect

好的,我找到了解决方法 "for now":

faceBounds = newChange.CGRectValue

这解决了 nil 问题,但根本没有转换。如果有人有更 "casting" 的方法,请随时 post 您的回答。

您可以使用 Foundation 的 NSRectToCGRect():

if let newValue = change?[NSKeyValueChangeNewKey] {
    print("\(newValue)")
    faceBounds = NSRectToCGRect(newValue)
    print("\(faceBounds)" + " in controller")
    dispatch_async(dispatch_get_main_queue(),{ () -> Void in self.updateFaceRectView()})
}