Chapter 2. Optional Types, Structures, & Enumerations

Programming is hard and debugging is harder, but maintaining and debugging large programs that run asynchronously and concurrently is hardest. It makes sense to place the burden of checking certain runtime properties of your program on the compiler rather than the developer. Swift’s optional types and structures let you tell the compiler more about your program now so that you spend less time debugging later. These features rely on a combination of compile-time checks and runtime techniques that, in most cases, do not reduce performance.

Optional Types Exterminate Nil-Value Bugs

Programs represent uninitialized or absent values with nil (a.k.a., null). If your code fails to handle a nil value anywhere one can occur, bad things can happen. So Swift incorporated the might-be-nil versus can-never-be-nil distinction into its static type system. These are called “just” and “maybe” in Haskell. For example, suppose you are trying to extract the “Content-Type” entry from the header fields of an HTTP request. You have the header fields represented as a dictionary with String keys and values:

let headerFields: [String: String] = 

Swift uses subscript notation to look up the value of a given key in a dictionary:

let contentType = headerFields["Content-Type"]

and Swift will infer a type for contentType. But that type is not “String”! It is “String?” with a question mark, because String represents a value that can never be nil, whereas ...

Get Extending Swift Value(s) to the Server now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.