Warning Converting Optional to StringMay 29, 2017 · 2 minute read
If you have converted a project to Swift 3.1 you have no doubt come across the slightly annoying warning about String interpolation for an optional value.
Converting an Optional to a String
The warning comes anytime you rely on the default conversion of an optional value to a String:
var optionalValue: Int? = 42 print("Value is \(optionalValue)") // Warning // "Value is Optional(42)"
This works but starting with Swift 3.1 gives you a warning. I think the idea is that you may overlook that you are converting an optional to a String and accidentally display the ugly details to the user. I am not sure how big a problem that was but Xcode suggests two ways to remove the warning:
The first way is to explicitly convert the type to a String using
print("Value is ",String(describing: optionalValue)) // "Value is Optional(42)"
This works fine and is what I ended up doing but is somewhat verbose. The second way is to give a default value:
print("Value is \(optionalValue ?? 0)") // "Value is 42"
The problem with this is there is often no sensible default to use here when the value is
nil (that is often the reason we are using an optional). A third way is to add an explicit cast to show you know what is going on:
print("Value is \(optionalValue as Int?)") // "Value is Optional(42)"
Another workaround I saw from Ole Begemann in his post on Optionals and String Interpolation is to use a custom optional string coalescing operator. Other than trying to avoid printing optionals I don’t have any better suggestions.