SwiftStyleGuide
PureSwift Official Swift Style Guide
Install / Use
/learn @PureSwift/SwiftStyleGuideREADME
The PureSwift Official Swift Style Guide
Table of Contents
- Correctness
- Naming
- Code Organization
- Spacing
- Comments
- Classes and Structures
- Function Declarations
- Function Calls
- Closure Expressions
- Types
- Functions vs Methods
- Memory Management
- Access Control
- Control Flow
- Golden Path
- Semicolons
- Parentheses
- Multi-line String Literals
- References
Correctness
Strive to make your code compile without warnings. This rule informs many style decisions such as using #selector types instead of string literals.
Naming
Descriptive and consistent naming makes software easier to read and understand. Use the Swift naming conventions described in the API Design Guidelines. Some key takeaways include:
- striving for clarity at the call site
- prioritizing clarity over brevity
- using camel case (not snake case)
- using uppercase for types (and protocols), lowercase for everything else
- including all needed words while omitting needless words
- using names based on roles, not types
- sometimes compensating for weak type information
- striving for fluent usage
- beginning factory methods with
make - naming methods for their side effects
- verb methods follow the -ed, -ing rule for the non-mutating version
- noun methods follow the formX rule for the mutating version
- boolean types should read like assertions
- protocols that describe what something is should read as nouns
- protocols that describe a capability should end in -able or -ible
- using terms that don't surprise experts or confuse beginners
- generally avoiding abbreviations
- using precedent for names
- preferring methods and properties to free functions
- casing acronyms and initialisms uniformly up or down
- giving the same base name to methods that share the same meaning
- avoiding overloads on return type
- choosing good parameter names that serve as documentation
- preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates
- labeling closure and tuple parameters
- taking advantage of default parameters
Prose
When referring to methods in prose, being unambiguous is critical. To refer to a method name, use the simplest form possible.
- Write the method name with no parameters. Example: Next, you need to call
addTarget. - Write the method name with argument labels. Example: Next, you need to call
addTarget(_:action:). - Write the full method name with argument labels and types. Example: Next, you need to call
addTarget(_: Any?, action: Selector?).
For the above example using UIGestureRecognizer, 1 is unambiguous and preferred.
Pro Tip: You can use Xcode's jump bar to lookup methods with argument labels. If you’re particularly good a mashing lots of keys simultaneously, put the cursor in the method name and press Shift-Control-Option-Command-C (all 4 modifier keys) and Xcode will kindly put the signature on your clipboard.

Class Prefixes
Swift types are automatically namespaced by the module that contains them and you should not add a class prefix such as NS or ABC. If two names from different modules collide you can disambiguate by prefixing the type name with the module name. However, only specify the module name when there is possibility for confusion which should be rare.
import SomeModule
let myClass = MyModule.UsefulClass()
Delegates
When creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.)
Preferred:
func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String)
func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool
Not Preferred:
func didSelectName(namePicker: NamePickerViewController, name: String)
func namePickerShouldReload() -> Bool
Use Type Inferred Context
Use compiler inferred context to write shorter, clear code. (Also see Type Inference.)
Preferred:
let selector = #selector(viewDidLoad)
view.backgroundColor = .red
let toView = context.view(forKey: .to)
let view = UIView(frame: .zero)
Not Preferred:
let selector = #selector(ViewController.viewDidLoad)
view.backgroundColor = UIColor.red
let toView = context.view(forKey: UITransitionContextViewKey.to)
let view = UIView(frame: CGRect.zero)
Generics
Generic type parameters should be descriptive, upper camel case names. When a type name doesn't have a meaningful relationship or role, use a traditional single uppercase letter such as T, U, or V.
Preferred:
struct Stack<Element> { ... }
func write<Target: OutputStream>(to target: inout Target)
func swap<T>(_ a: inout T, _ b: inout T)
Not Preferred:
struct Stack<T> { ... }
func write<target: OutputStream>(to target: inout target)
func swap<Thing>(_ a: inout Thing, _ b: inout Thing)
Language
Use US English spelling to match Apple's API.
Preferred:
let color = "red"
Not Preferred:
let colour = "red"
Code Organization
Use extensions to organize your code into logical blocks of functionality. Each extension should be set off with a // MARK: - comment to keep things well-organized.
Protocol Conformance
In particular, when adding protocol conformance to a model, prefer adding a separate extension for the protocol methods. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.
Preferred:
final class MyTableViewController: UIViewController {
// class stuff here
}
// MARK: - UITableViewDataSource
extension MyTableViewController: UITableViewDataSource {
// table view data source methods
}
// MARK: - UIScrollViewDelegate
extension MyTableViewController: UIScrollViewDelegate {
// scroll view delegate methods
}
Not Preferred:
class MyTableViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate {
// all methods
}
Since the compiler does not allow you to re-declare protocol conformance in a derived class, it is not always required to replicate the extension groups of the base class. This is especially true if the derived class is a terminal class and a small number of methods are being overridden. When to preserve the extension groups is left to the discretion of the author.
For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions.
Unused Code
Unused (dead) code, including Xcode template code and placeholder comments should be removed.
Preferred:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Database.contacts.count
}
Not Preferred:
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return Database.contacts.count
}
Minimal Imports
Import only the modules a source file requires. For example, don't import UIKit when importing Foundation will suffice.
Preferred:
import UIKit
var view: UIView
var deviceModels: [String]
Preferred:
import Foundation
import UIKit
var view: UIView
var deviceModels: [NSObject]
Preferred:
import Foundation
var deviceModels: [String]
Not Preferred:
import UIKit
var deviceModels: [String]
Spacing
- Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode and in the Project settings as shown below:

- Method braces and other braces (
if/else/switch/whileetc.) always open on the same line as the statement but close on a new line. - Tip: You can re-indent by selecting some code (or Command-A to select all) and then Control-I (or Editor ▸ Structure ▸ Re-Indent in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that.
Preferred:
if user.isHappy {
// Do something
} else {
// Do something else
}
Not Preferred
Security Score
Audited on Jul 31, 2024
