#74: Optional Chaining in Swift

Optional chaining is more flexible than it first appears. It works with properties, methods and even subscripts.

let count = user.profile?.friends.count
let image = cache["avatar"]?.resized(to: .thumbnail)
let title = controller.currentPage?.title()

If any step in the chain is nil, the whole expression becomes nil.

This makes deeply nested lookups much cleaner than repeated if let blocks when you only need a derived value.


I'm also on Twitter and GitHub.

Subscribe via RSS.