Warning Converting Optional to String

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 String(describing:):

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 Optional(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.

Never miss a post!

iOS Size Classes Cheat Sheet

Subscribe and get my free iOS Size Classes Cheat Sheet

Success! Now check your email to confirm your subscription and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
No time to watch WWDC videos?

Sign up to get my iOS posts direct to your inbox and I will send you a free PDF of my iOS Size Classes Cheat Sheet.

OK! Check your inbox (or spam folder) for an email to confirm your details and download your free guide to iOS Size Classes.

There was an error submitting your subscription. Please try again.

Unsubscribe at any time.
Archives Categories