[swift-evolution] mandatory "?" suffix for identifiers associated with optional types

Amir Michail a.michail at me.com
Fri Dec 4 09:20:45 CST 2015

So for example the following (probable) bug would result in a compile error:

let f = x < 5 // where x is optional and could be nil

If that was really what was intended, you would need to write:

let f = x? < 5

Similarly, the rule would also apply for functions that return an optional type:

let f = x()? < 5

A major advantage of this approach is it would encourage programmers to unwrap optionals early to avoid writing “?” and “?!" frequently in their code.

Note that conditional chaining would just make use of the existing “?” suffix. There is no need to add another “?” after that.

let f = x?.g?.h
let f = x()?.g?.h

As for implicitly unwrapped optionals, a “?” suffix would only be used when you want to treat a value as an optional (e.g., when comparing it to nil). For example, for x of type Int?, one could write:

let y = (x? == nil) ? 0 : x

More information about the swift-evolution mailing list