Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 879
Greg Avatar asked Dec 01 '15 03:12

Greg


3 Answers

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)
like image 114
Leo Avatar answered Nov 15 '22 23:11

Leo


let number:NSNumber? = NSNumber(integer: 125)


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

let integerValue = number?.integerValue ?? 0
like image 38
Leo Dabus Avatar answered Nov 16 '22 00:11

Leo Dabus


orderNumberInt = orderNum?.intValue

This is the best way to do it in Swift.

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

like image 28
Ankit Rathi Avatar answered Nov 16 '22 01:11

Ankit Rathi