Search code examples
swiftintint32uint16

Swift: Convert Int16 to Int32 (or NSInteger)


I'm really stuck! I'm not an expert at ObjC, and now I am trying to use Swift. I thought it would be much simpler, but it wasn't. I remember Craig said that they call Swift “Objective-C without C”, but there are too many C types in OS X's foundation. Documents said that many ObjC types will automatically convert, possibly bidirectionally, to Swift types. I'm curious: how about C types?

Here's where I'm stuck:

//array1:[String?], event.KeyCode.value:Int16
let s = array1[event.keyCode.value]; //return Int16 is not convertible to Int

I tried some things in ObjC:

let index = (Int) event.keyCode.value; //Error

or

let index = (Int32) event.keyCode.value; //Error again, Swift seems doesn't support this syntax

What is the proper way to convert Int16 to Int?


Solution

  • To convert a number from one type to another, you have to create a new instance, passing the source value as parameter - for example:

    let int16: Int16 = 20
    let int: Int = Int(int16)
    let int32: Int32 = Int32(int16)
    

    I used explicit types for variable declarations, to make the concept clear - but in all the above cases the type can be inferred:

    let int16: Int16 = 20
    let int = Int(int16)
    let int32 = Int32(int16)