I have an objective c property that has been declared as
@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
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
'
EDIT::::
Dict init, there are other objects in dict besides integers
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
. You can first obtain the NSNumber
and then call intValue
on it:
if let bufferSize = dict["bufferSize"] as? NSNumber {
sharedExample.xmlBufferSize = bufferSize.intValue
}
The 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
. The then-branch will only execute if dict["bufferSize"]
exists and is an 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.)
您需要将NSNumber转换为Int32。
sharedExample.xmBufferSize = dict["bufferSize"]!.intValue
Use type conversion, not as:
sharedExample.xmBufferSize = Int32(dict["bufferSize"] as! Int)
That should work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.