Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Int to int in swift?

Tags:

ios

swift

I have a variable called number of type Int

var number = value!.integerValue as Int

Now I have to create a NSNumber object using that value.

I am trying to use this constructor

value = NSNumber(int: number)

, but it does not work.

It expect the primitive type int, not Int I guess.

Anyone know how to get around this?

Thanks!

like image 843
ppalancica Avatar asked May 05 '15 18:05

ppalancica


People also ask

How do you convert int to text 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.

Can you convert string to Int swift?

Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

What does int mean in Swift?

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 .


1 Answers

You just do value = number

As you can see in the documentation:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

the native swift number types generally bridge directly to NSNumber.

Numbers

Swift automatically bridges certain native number types, such as Int and Float, to NSNumber. This bridging lets you create an NSNumber from one of these types:

SWIFT

let n = 42
let m: NSNumber = n
It also allows you to pass a value of type Int, for example, to an argument expecting an NSNumber. Note that because NSNumber can contain a variety of different types, you cannot pass it to something expecting an Int value.

All of the following types are automatically bridged to NSNumber:

Int
UInt
Float
Double
Bool

Swift 3 update

In Swift 3, this bridging conversion is no longer automatic and you have to cast it explicitly like this:

let n = 42
let m: NSNumber = n as NSNumber
like image 103
Dima Avatar answered Oct 24 '22 15:10

Dima