Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 764
Wilson Luniz Avatar asked Jan 15 '15 17:01

Wilson Luniz


People also ask

What is the difference between Int32 and Int64 in Swift?

In most cases, you don't need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform's native word size: On a 32-bit platform, Int is the same size as Int32. On a 64-bit platform, Int is the same size as Int64.

How to assign Int value to String in Swift?

To convert an Int value to a String value in Swift, use String(). String() accepts integer as argument and returns a String value created using the given integer value.

What is Int32 in Swift?

A 32-bit signed integer value type.


1 Answers

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)
like image 148
Antonio Avatar answered Oct 25 '22 05:10

Antonio