Swift Style Guide Updated for Swift 3

We’ve updated our popular Swift Style Guide for Swift 3 – check out the changes inside! By Ray Fix.

Leave a rating/review
Save for later
Share

Good news – we have updated our Swift Style Guide for Swift 3!

Here at raywenderlich.com, we want to have a consistent style for you in our tutorials, books, videos, and conference materials. We believe it improves readability, and makes our content easier and quicker to understand. Our style guide helps us accomplish this.

This update resolves dozens of issues and enhancements from the community since our last update in April.

Let’s look at some of the highlights in this latest update.

The Grand Renaming

This year, alongside the release of Swift 3, the Swift community tackled naming in a major way.

Basically, the core team recognized that libraries using consistent, predictable names significantly elevate the overall development experience and determine the character of the language.

Not only did the community formalize a consistent set of naming rules, they also adopted these rules in both the standard library and in how Objective-C libraries are imported into Swift projects. The core team decided that the massive breakage would be worth it in the long run. We agree. It’s that good.

The new naming rules are set forth in an important document called the API Design Guidelines, which provides numerous examples and some rationale for the changes.

The Swift 3 update to our Swift Style Guide fully embraces these rules and enumerates the important takeaways that you should keep in your head as you are writing code. For example:

  • Creating a factory method? It should begin with make.
  • Writing a non-mutating method that returns a modified version of the model? It should end with -ed or -ing.

Armed with these rules and with all of the good examples from the Standard library and Cocoa, writing your own Swifty APIs should become secondhand nature in no time.

name_it

In addition to the API Design Guidelines, our style guide spells out some additional recommendations. For example, delegates. Delegates should always have a first unnamed parameter that specifies the delegate’s source.

 
func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String)

func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool
 

Context is Everything

Recognizing context is something Swift does really well. Our previous style guide emphasized using compiler type inference to make code shorter and easier to understand. This update further encourages utilization of context.

In his WWDC 2016 session on the API Design Guidelines, Doug Gregor (core team & compiler engineer extraordinaire) demonstrates how we can reduce cognitive load by using context, strong types and omitting needless words. One of his examples focuses on how Objective-C types map much better into Swift 3. The old Swift 2 code:

 
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
 

in Swift 3, becomes the more readable:

 
let cal = Calendar(identifier: .gregorian)
 

It’s a nice example. Not only is it more readable but you have the piece of mind that the Swift compiler is enforcing guarantees about correctness. By the way, I see what you did there using the .gregorian example, Doug Gregor. :] Similarly, our updated style guide recommends that you use context to write shorter code where clarity is not being sacrificed. For example:

 
let view = UIView(frame: .zero)

view.backgroundColor = .red
 

Access Control

Swift 3 changed the access control keywords, adding fileprivate and making private specify lexical scope privacy.

Although many tutorials may omit access control to keep things simple, encapsulation with private and fileprivate is encouraged.

There are rumblings that there may be changes to access control in Swift 4. In the meantime, authors should use private when possible and only fileprivate when it is required. For example when it is used by an extension in the same file. private and fileprivate mean the same thing at file scope, and in this case you should prefer private.

Space Wars

space_wars

Tabs versus spaces. Two space indents versus four. Space before colons for type declarations. These are almost religious issues that seem to come up every time we do an update.

We have decided to continue to use two-space indenting as it is the best choice for printed material in which page real-estate is limited. That said, we have added some additional recommendations about white space this time:

  1. Keep line lengths reasonable.
  2. No trailing whitespace.
  3. One newline at the end of the file.

Formatting guard statements was also an item of some discussion. Should they be one-liners or always span multiple lines? How should you indent multiple let bindings and conditions? How should the else clause be indented?

In the end, we decided to not make a specific rule about it, and leave it to the discretion of the author. Perhaps a universal standard will emerge. We will keep an eye on some of the larger open source projects and code written by luminaries in the Swift community to see if one does.

Referring to Methods in Prose

The way that methods will be referred to in prose (e.g. tutorials and books) has also changed. Since external argument names now often don’t include the type name, there are potentially cases where even if you write out all of the external parameters, your method can still be ambiguous. In these cases, the types should be included.

In general, our guidance is when referring to a method name in prose, use the simplest form possible that’s not ambiguous.

  1. Write the method name with no parameters. Example: Next, you need to call the method addTarget.
  2. Write the method name with argument labels. Example: Next, you need to call the method addTarget(_:action:).
  3. Write the full method name with argument labels and types. Example: Next, you need to call the method addTarget(_: Any?, action: Selector?).

Resisting Feature Creep and Removing Rules

There is a tendency to want to keep adding rules to a style guide. However, doing so can make it less approachable for a newcomer. We have been mindful to keep the number of rules relatively small and even remove rules when possible. Swift lets us do that.

For example, a section on struct initialization could be completely removed as Swift 3 makes it impossible to compile the discouraged form. Thanks Swift 3!