How to convert Swift optional NSNumber to optional Int? (any improvements on my code?)
Asked Answered
B

5

13

What would be the shortest/cleanest way to convert an Optional Number to an Optional Int in Swift?

Is there a better way than this? (see below)

let orderNumberInt : Int?
if event.orderNum != nil {
    orderNumberInt = Int(event.orderNum!)
} else {
    orderNumberInt = nil
}
Bonds answered 1/12, 2015 at 3:33 Comment(0)
P
26

I think most easiest way is

var orderNumberInt = orderNum?.intValue

Also, you can do it like this

var orderNum:NSNumber? = NSNumber(int: 12)
var orderNumberInt:Int? = (orderNum != nil) ? Int(orderNum!) : nil
print(orderNumberInt)
Putrescent answered 1/12, 2015 at 3:48 Comment(3)
int is the initialiser for Int32Puente
thanks guys - you made it hard to choose which was correct first :) But what I'm after specifically here would be "var orderNumberInt = orderNum?.integerValue" so I choose this one, hope thats okBonds
FYI, this method has been renamed from integerValue to intValue in Swift 4.Twinkling
P
5
let number:NSNumber? = NSNumber(integer: 125)


if let integerValue = number?.integerValue {
    print(integerValue)
}

let integerValue = number?.integerValue ?? 0
Puente answered 1/12, 2015 at 3:50 Comment(0)
C
2
orderNumberInt = orderNum?.intValue

This is the best way to do it in Swift.

Reference: https://developer.apple.com/documentation/foundation/nsnumber/1412554-intvalue

Chui answered 17/7, 2020 at 10:27 Comment(0)
B
0

You can use if let syntax

    var number: NSNumber?
    if let value = number as? Int {
        // get int value
    } else {

    }
Bipartite answered 1/12, 2015 at 3:39 Comment(0)
S
0

I am using this simple conversion:

// lets consider following vars
var nsNum: NSNumber?
var oiNum: Int? // oi - optional Int

NSNumber to optional Int?

nsNum = NSNumber.init(value: 18)
oiNum = nsNum as? Int

optional Int? to NSNumber

oiNum = 19
nsNum = oiNum as NSNumber?

p.s. I am new to swift, so if something wrong, feel free to correct :-)

Selves answered 6/12, 2019 at 9:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.