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
}
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)
let number:NSNumber? = NSNumber(integer: 125)
if let integerValue = number?.integerValue {
print(integerValue)
}
let integerValue = number?.integerValue ?? 0
orderNumberInt = orderNum?.intValue
This is the best way to do it in Swift.
Reference: https://developer.apple.com/documentation/foundation/nsnumber/1412554-intvalue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With