swift 强制将 objective-c int 分配为 Int32 然后崩溃
swift forcing objective-c int to be assigned as Int32 then crashing
我有一个 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
'
编辑::::
dict init,dict中除了整数还有其他对象
var bufferSize:Int = 1024
var dict = Dictionary<String, AnyObject>() = ["bufferSize":bufferSize]
使用类型转换,而不是:
sharedExample.xmBufferSize = Int32(dict["bufferSize"] as! Int)
应该可以。
您需要将 NSNumber 转换为 Int32。
sharedExample.xmBufferSize = dict["bufferSize"]!.intValue
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-branch
(注意:如果 intValue
给出了错误的类型,您也可以尝试 integerValue
,或者根据需要转换结果整数 - CInt(bufferSize.integerValue)
。Swift 不会不同整数类型之间不做隐式转换,所以需要精确匹配。)
我有一个 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
'
编辑::::
dict init,dict中除了整数还有其他对象
var bufferSize:Int = 1024
var dict = Dictionary<String, AnyObject>() = ["bufferSize":bufferSize]
使用类型转换,而不是:
sharedExample.xmBufferSize = Int32(dict["bufferSize"] as! Int)
应该可以。
您需要将 NSNumber 转换为 Int32。
sharedExample.xmBufferSize = dict["bufferSize"]!.intValue
dict
中的值是一个 NSNumber
,不能强制转换或直接转换为 Int32
。您可以先获取 NSNumber
,然后对其调用 intValue
:
if let bufferSize = dict["bufferSize"] as? NSNumber {
sharedExample.xmlBufferSize = bufferSize.intValue
}
if let … as?
允许您验证该值确实是一个 NSNumber
,因为(如您所说)dict
中可以有其他类型的对象。只有 dict["bufferSize"]
存在并且是 NSNumber
.
(注意:如果 intValue
给出了错误的类型,您也可以尝试 integerValue
,或者根据需要转换结果整数 - CInt(bufferSize.integerValue)
。Swift 不会不同整数类型之间不做隐式转换,所以需要精确匹配。)