iosswiftswift2option-typensnumber

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
}

Solution

  • 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)