saikat bhakat saikat bhakat - 8 months ago 20
Swift Question

I am facing issue with Nil Coalescing in Swift

Is there a way of not using forced unwrapping in the nil coalescing operator, in Swift?

I tried using:

Int(errorCodeString?) ?? 500

But, this didn't work.

The overall code snippet is:

var errorCodeString: String?

errorCodeString = "404"

let actualErrorCode = Int(errorCodeString!) ?? 500

print("Actual Error Code: \(actualErrorCode)")


Sure. Use the nil coalescing operator twice, once to unwrap the String? and the second time to unwrap the Int?:

let actualErrorCode = Int(errorCodeString ?? "") ?? 500


Your errorCodeString is an optional String (aka String?). Performing errorCodeString ?? "" will either unwrap errorCodeString if it is not nil or replace it with "" if it is nil.

The result of that is passed to the Int initializer which takes a String. The Int(_:String) initializer turns that String into an Int? which either contains the integer value or nil if the String doesn't represent a valid Int. The second nil coalescing operator ?? unwraps that Int? or replaces it with 500 if the value is nil.

What you tried initially Int(errorCodeString?) ?? 500 doesn't work because following an optional with ? only conditionally unwraps it in an optional chain. In that case, you must follow the ? with a member access, method call, or indexing operator [].