vrwim vrwim - 1 year ago 89
Swift Question

Optional chaining for constructor calls?

I want to optionally cast an

to an
, but the initialiser method for
only takes
, so I can't pass an

Is there a way for me to compact this code so that it uses something like optional chaining?

// number: NSNumber?
let integer = number == nil ? nil : Int(number!)

Answer Source

The Int constructors don't take optional arguments. You could "wrap" the construction into map():

let number : NSNumber? = ...
let n = number.map { Int($0) } // `n` is an `Int?`

But here it is easier to use the integerValue property of NSNumber with optional chaining:

let n = number?.integerValue // `n` is an `Int?`

or just

let n = number as? Int // `n` is an `Int?`

since Swift "bridges" between NSNumber and Int automatically.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download