快速强制objective-c int被赋值为Int32然后崩溃



我有一个objective - c属性被声明为

@property int xmBufferSize;

如果我做sharedExample.xmBufferSize = 1024,它就工作得很好但当我试图从另一个变量

为该属性设置整数值时
var getThat:Int = dict["bufferSize"]!.integerValue
sharedExample.xmBufferSize = getThat

它不能做以上

Cannot assign a value of type 'Int' to a value of type 'Int32'

如果我强制它为

sharedExample.xmBufferSize =dict["bufferSize"] as! Int32

程序正在崩溃,报错

Could not cast value of type '__NSCFNumber' to 'Swift.Int32 '

编辑::::
字典初始化,字典中除了整数还有其他对象

var bufferSize:Int = 1024
var dict = Dictionary<String, AnyObject>() = ["bufferSize":bufferSize]

"dict"为NSNumber,不能强制转换,也不能直接转换为Int32。您可以首先获得NSNumber,然后在其上调用intValue:

if let bufferSize = dict["bufferSize"] as? NSNumber {
    sharedExample.xmlBufferSize = bufferSize.intValue
}

if let … as?允许您验证该值确实是NSNumber,因为(如您所说)dict中可以有其他类型的对象。只有当dict["bufferSize"]存在并且是NSNumber时,then分支才会执行。

(注意:如果intValue给出了错误的类型,您也可以尝试integerValue,或者根据需要转换结果整数- CInt(bufferSize.integerValue)。Swift不做不同整数类型之间的隐式转换,所以你需要精确匹配。

您需要将NSNumber转换为Int32。

sharedExample.xmBufferSize = dict["bufferSize"]!.intValue

使用类型转换,而不是as:

sharedExample.xmBufferSize = Int32(dict["bufferSize"] as! Int)

应该可以。