Nil Coalescing Operator with mixed types

Cognitio

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.

OOPer

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"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Nil Coalescing Operator Swift

Nil coalescing operator for dictionary

Swift nil coalescing operator with array

Why is the nil coalescing operator ?? returning nil?

Compiler not understanding Nil Coalescing Operator on NSTimeInterval

Nil-Coalescing Operator without changing value

Conditional operator with mixed data types?

Using nil-coalescing operator with try? for function that throws and returns optional

What is the role of the nil-coalescing operator "??" in optional chaining?

Coalescing Swift operator for an empty non-nil string

Why does the nil coalescing operator wrap an implicitly unwrapped default value?

Swift 4.2, Xcode 10.2 nil coalescing operator warning

Use printf for ternary operator arguments with mixed types

swift nil coalescing with doubles

Left side of nil coalescing operator '??' has non-optional type 'String', so the right side is never used

Type inference fails when using nil-coalescing operator with two optionals

Why doesn't Swift nil-coalescing ternary operator return unwrapped type?

Maybe coalescing operator

Opposite of nullish coalescing operator

Is there a "null coalescing" operator in JavaScript?

Nullish Coalescing operator in JavaScript

Null coalescing operator (??) with return

PHP - null coalescing operator

Coalescing operator in linq query

Null coalescing operator override

Use of coalescing operator in Typescript

Nullish coalescing operator not working or not enabled?

Null coalescing operator, unpredictable behavior

Nullish coalescing vs logical OR operator