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

Greg picture Greg · Dec 1, 2015 · Viewed 16.2k times · Source

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
}

Answer

Leo picture Leo · Dec 1, 2015

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)