简体   繁体   English

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

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

I have an objective c property that has been declared as 我有一个已被声明为的客观c属性

@property int xmBufferSize;

If I do sharedExample.xmBufferSize = 1024 it just works fine but when I am trying to set an integer value for that property from another variable 如果我做sharedExample.xmBufferSize = 1024它只是工作正常,但当我试图从另一个变量设置该属性的整数值

var getThat:Int = dict["bufferSize"]!.integerValue
sharedExample.xmBufferSize = getThat

It can't do above 它不能做到以上

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

If I force this to 如果我强迫这个

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

It is crashing with Error 它正在崩溃与错误

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

EDIT:::: 编辑::::
Dict init, there are other objects in dict besides integers Dict init,除了整数之外还有dict中的其他对象

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

The value in dict is an NSNumber , which cannot be cast or directly converted to Int32 . dict的值是NSNumber ,无法NSNumber转换或直接转换为Int32 You can first obtain the NSNumber and then call intValue on it: 您可以先获取NSNumber ,然后在其上调用intValue

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

The if let … as? if let … as? allows you to verify that the value is indeed an NSNumber , since (as you said) there can be other types of objects in dict . 允许你验证该值确实是一个NSNumber ,因为(如你所说)在dict可以有其他类型的对象。 The then-branch will only execute if dict["bufferSize"] exists and is an NSNumber . then-branch只有在dict["bufferSize"]存在并且是NSNumber时才会执行。

(Note: You can also try integerValue if intValue gives the wrong type, or convert the resulting integer – CInt(bufferSize.integerValue) – as needed. Swift doesn't do implicit conversions between different integer types, so you need to match exactly.) (注意:如果intValue给出了错误的类型,你也可以尝试integerValue ,或者根据需要转换生成的整数 - CInt(bufferSize.integerValue) integerValue不会在不同的整数类型之间进行隐式转换,所以你需要完全匹配。 )

您需要将NSNumber转换为Int32。

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

Use type conversion, not as: 使用类型转换,而不是:

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

That should work. 这应该工作。

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

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