UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Warnings for ambiguous none cases

Available from Swift 5.1

Paul Hudson      @twostraws

Swift’s optionals are implemented as an enum of two cases: some and none. This gave rise to the possibility of confusion if we created our own enums that had a none case, then wrapped that inside an optional.

For example:

enum BorderStyle {
    case none
    case solid(thickness: Int)
}

Used as a non-optional this was always clear:

let border1: BorderStyle = .none
print(border1)

That will print “none”. But if we used an optional for that enum – if we didn’t know what border style to use – then we’d hit problems:

let border2: BorderStyle? = .none
print(border2)

That prints “nil”, because Swift assumes .none means the optional is empty, rather than an optional with the value BorderStyle.none.

In Swift 5.1 this confusion now prints a warning: “Assuming you mean 'Optional.none'; did you mean 'BorderStyle.none' instead?” This avoids the source compatibility breakage of an error, but at least informs developers that their code might not quite mean what they thought.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Other changes in Swift 5.1…

Download all Swift 5.1 changes as a playground Link to Swift 5.1 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.