swift - Swift 中的转换未按预期工作

标签 swift casting option-type

这是我的代码的一部分:

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/

相关文章:

iOS, swift : animation controlled by gesture

ios - NSLayoutAttribute中的Top和TopMargin有什么区别?

c - 我是否要转换 malloc 的结果?

c - 提议的 C23 `_Either` 类型到底是什么?

swift - 为什么我仍然需要解包 Swift 字典值?

ios - UIApplicationOpenURLOptionsKey.sourceApplication 可以为零吗?

ios - 当具有动态单元格高度的 UITableview 放置在里面时,如何扩展/缩小 UICollectionViewCell 高度?

java - Java cast 运算符如何工作?

c# - 将对象列表转换为 List 与 IList

Swift:关于将 nil 分配给 var