繁体   English   中英

swift强制将objective-c int指定为Int32然后崩溃

[英]swift forcing objective-c int to be assigned as Int32 then crashing

我有一个已被声明为的客观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]

dict的值是NSNumber ,无法NSNumber转换或直接转换为Int32 您可以先获取NSNumber ,然后在其上调用intValue

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

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

(注意:如果intValue给出了错误的类型,你也可以尝试integerValue ,或者根据需要转换生成的整数 - CInt(bufferSize.integerValue) integerValue不会在不同的整数类型之间进行隐式转换,所以你需要完全匹配。 )

您需要将NSNumber转换为Int32。

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

使用类型转换,而不是:

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

这应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM