3

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]
Mord Fustang
  • 1,523
  • 4
  • 40
  • 71
  • `getThat` is `Int`. Either change `getThat` to `Int32` and replace `.integerValue` with `.intValue` or `sharedExample.xmlBufferSize = Int32(getThat)`. – zrzka Jul 14 '15 at 20:03
  • As above a part of the problem is different sized of the integer. It is best to explicitly set these, `uint32_t` in Objective-C and `Int32` in Swift. Then you know exactly what the sizes are. Swift does not handle size casts implicitly so you have to know. – zaph Jul 14 '15 at 20:29

3 Answers3

5

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.)

Arkku
  • 41,011
  • 10
  • 62
  • 84
0

You need to convert your NSNumber to Int32.

sharedExample.xmBufferSize = dict["bufferSize"]!.intValue
Tomáš Linhart
  • 13,509
  • 5
  • 51
  • 54
-1

Use type conversion, not as:

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

That should work.

Duncan C
  • 128,072
  • 22
  • 173
  • 272