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
Writing a non-mutating method that returns a modified version of the model? It should end with
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.
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
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
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.
fileprivate mean the same thing at file scope, and in this case you should prefer
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:
- Keep line lengths reasonable.
- No trailing whitespace.
- One newline at the end of the file.
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.
- Write the method name with no parameters. Example: Next, you need to call the method
- Write the method name with argument labels. Example: Next, you need to call the method
- 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!
Where to Go From Here?
There are numerous other small changes not mentioned here–everything has been updated to valid Swift 3, the Organization and Bundle ID are now specified for Xcode projects and more. Over time, you will see our tutorials and books adopt this style.
We encourage you to read through the entire guide as it is not that long. Also, be sure to check out the API Design Guidelines which is linked from the guide. Finally, it is worth your time to watch the WWDC session about the about the why of API design guidelines.
The style guide has been improved by individuals both inside and outside of raywenderlich.com. I personally would like to thank the many people that have helped this year to make it a better document and added to the discussion. If you don’t see your name in the credits and should be, drop me a line or send a pull request.
This is a living document. If you want to get even more involved, open (or reopen) a Github issue and start a discussion. Typos and errors that need to be immediately fixed will go directly into the
master branch after a brief review period. A
update branch will handle larger changes for a future update next year. See the contributing guide for more information.
What do you like or not like? Leave a comment below.