Search code examples
swiftnulloption-typedefault-valuenull-coalescing-operator

Nil Coalescing Operator with mixed types


Is there any good concise swifty way to take an optional of a non-String type and get a String value that is either the String interpretation of that value if it is .some() or some default value if it is .none() besides the following:

let statusCode = (resp as? HTTPURLResponse)?.statusCode
let statusCodeString: String
if let statusCode = statusCode {
    statusCodeString = "\(statusCode)"
} else {
    statusCodeString = "None"
}

It just seems awfully verbose for a relatively simple thing, and it feels like I'm missing something obvious.

Just using the nil-coalescing operator doesn't work because you have to provide a default value of the same type.


Solution

  • You can write some thing like this:

    let statusCodeString = statusCode?.description ?? "None"
    

    Or if you want to work with some types which does not have the property description:

    let statusCodeString = statusCode.map{String(describing: $0)} ?? "None"