Swift: Convert Int16 to Int32 (or NSInteger)
Asked Answered
C

3

10

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?

Churchly answered 15/1, 2015 at 17:15 Comment(1)
Try let s = array1[Int(event.keyCode.value)]Araceli
D
27

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)
Derekderelict answered 15/1, 2015 at 17:20 Comment(0)
A
1

This is not how this type of casting works in Swift. Instead, use:

let a : Int16 = 1
let b : Int = Int(a)

So, you basically instantiate one variable on base of the other.

Abarca answered 15/1, 2015 at 17:19 Comment(0)
T
0

In my case "I was trying to convert core data Int16 to Int" explicit casting didn't worked. I did this way

let quantity_string:String = String(format:"%d",yourInt16value)
let quantity:Int = Int(quantity_string)
Travesty answered 23/8, 2018 at 19:5 Comment(1)
I don't know why direct casting not working "let int: Int = Int(int16)"Travesty

© 2022 - 2024 — McMap. All rights reserved.