*[Use Type Inferred Context](#use-type-inferred-context)
*[Generics](#generics)
*[Class Prefixes](#class-prefixes)
*[Language](#language)
*[Code Organization](#code-organization)
*[Protocol Conformance](#protocol-conformance)
*[Unused Code](#unused-code)
*[Minimal Imports](#minimal-imports)
*[Spacing](#spacing)
*[Comments](#comments)
*[Classes and Structures](#classes-and-structures)
*[Use of Self](#use-of-self)
*[Protocol Conformance](#protocol-conformance)
*[Computed Properties](#computed-properties)
*[Final](#final)
*[Function Declarations](#function-declarations)
*[Closure Expressions](#closure-expressions)
*[Types](#types)
*[Constants](#constants)
*[Static Methods and Variable Type Properties](#static-methods-and-variable-type-properties)
*[Optionals](#optionals)
*[Lazy Initialization](#lazy-initialization)
*[Type Inference](#type-inference)
*[Syntactic Sugar](#syntactic-sugar)
*[Functions vs Methods](#functions-vs-methods)
*[Memory Management](#memory-management)
*[Extending Lifetime](#extending-object-lifetime)
*[Access Control](#access-control)
*[Control Flow](#control-flow)
*[Golden Path](#golden-path)
*[Failing Guards](#failing-guards)
*[Semicolons](#semicolons)
*[Parentheses](#parentheses)
## 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](https://swift.org/documentation/api-design-guidelines/). Some key takeaways include:
- using camel case (not snake case) - `usingCamelCase`, not `using_snake_case`
- using uppercase for types (and protocols), lowercase for everything else
- including all needed words while omitting needless words, e.g. `func commitChanges()`, not `func commitTheChanges()`
- using names based on roles, not types, e.g. `var objects` or `var name`, not `var objectArray` or `var nameString`
- naming methods for their side effects
- verb methods follow the -ed, -ing rule for the non-mutating version
- boolean types should read like assertions
- protocols that describe _what something is_ should read as nouns, e.g. `StringLiteral`, `NSFastEnumeration`
- protocols that describe _a capability_ should end in _-able_ or _-ible_, e.g. `Disposable`, `Equatable`
- using terms that don't surprise experts or confuse beginners
- generally avoiding abbreviations
- preferring methods and properties to free functions
- 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
- 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.
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?)`.
For the above example using `UIGestureRecognizer`, 1 is unambiguous and preferred.
### Class Prefixes
Swift types are automatically namespaced by the module that contains them and you should not add a class prefix such as RW. 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.
```swift
importSomeModule
letmyClass=MyModule.UsefulClass()
```
### Delegates
When creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.)
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`.
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.
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. An exception is when your tutorial or book instructs the user to use the commented code.
Aspirational methods not directly associated with the tutorial whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods.
// #warning Incomplete implementation, return the number of rows
returnDatabase.contacts.count
}
```
### Minimal Imports
Keep imports minimal. For example, don't import `UIKit` when importing `Foundation` will suffice.
## Spacing
* Method braces and other braces (`if`/`else`/`switch`/`while` etc.) always open on the next line of the statement and close on a new line as well.
**Preferred:**
```swift
ifuser.isHappy
{
// Do something
}
else
{
// Do something else
}
```
**Not Preferred:**
```swift
ifuser.isHappy{
// Do something
}
else{
// Do something else
}
```
* There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods.
* Colons always have no space on the left and one space on the right. Exceptions are the ternary operator `? :`, empty dictionary `[:]` and `#selector` syntax for unnamed parameters `(_:)`.
**Preferred:**
```swift
classTestDatabase:Database
{
vardata:[String:CGFloat]=["A":1.2,"B":3.2]
}
```
**Not Preferred:**
```swift
classTestDatabase:Database
{
vardata:[String:CGFloat]=["A":1.2,"B":3.2]
}
```
* Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified.
* Avoid trailing whitespaces at the ends of lines.
* Add a single newline character at the end of each file.
## Comments
When they are needed, use comments to explain **why** a particular piece of code does something. Comments must be kept up-to-date or deleted.
Avoid block comments inline with code, as the code should be as self-documenting as possible. *Exception: This does not apply to those comments used to generate documentation.*
## Classes and Structures
### Which one to use?
Remember, structs have [value semantics](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_144). Use structs for things that do not have an identity. An array that contains [a, b, c] is really the same as another array that contains [a, b, c] and they are completely interchangeable. It doesn't matter whether you use the first array or the second, because they represent the exact same thing. That's why arrays are structs.
Classes have [reference semantics](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_145). Use classes for things that do have an identity or a specific life cycle. You would model a person as a class because two person objects are two different things. Just because two people have the same name and birthdate, doesn't mean they are the same person. But the person's birthdate would be a struct because a date of 3 March 1950 is the same as any other date object for 3 March 1950. The date itself doesn't have an identity.
Sometimes, things should be structs but need to conform to `AnyObject` or are historically modeled as classes already (`NSDate`, `NSSet`). Try to follow these guidelines as closely as possible.
### Example definition
Here's an example of a well-styled class definition:
```swift
classCircle:Shape
{
varx:Int,y:Int
varradius:Double
vardiameter:Double
{
get
{
returnradius*2
}
set
{
radius=newValue/2
}
}
init(x:Int,y:Int,radius:Double)
{
self.x=x
self.y=y
self.radius=radius
}
convenienceinit(x:Int,y:Int,diameter:Double)
{
self.init(x:x,y:y,radius:diameter/2)
}
overridefuncarea()->Double
{
returnDouble.pi*radius*radius
}
}
extensionCircle:CustomStringConvertible
{
vardescription:String
{
return"center = \(centerString) area = \(area())"
}
privatevarcenterString:String
{
return"(\(x),\(y))"
}
}
```
The example above demonstrates the following style guidelines:
+ Specify types for properties, variables, constants, argument declarations and other statements with a space after the colon but not before, e.g. `x: Int`, and `Circle: Shape`.
+ Define multiple variables and structures on a single line if they share a common purpose / context.
+ Indent getter and setter definitions and property observers.
+ Don't add modifiers such as `internal` when they're already the default. Similarly, don't repeat the access modifier when overriding a method.
+ Organize extra functionality (e.g. printing) in extensions.
+ Hide non-shared, implementation details such as `centerString` inside the extension using `private` access control.
### Use of Self
For conciseness, always use `self` to access an object's properties or invoke its methods.
### Computed Properties
For conciseness, if a computed property is read-only, omit the get clause. The get clause is required only when a set clause is provided.
**Preferred:**
```swift
vardiameter:Double
{
returnradius*2
}
```
**Not Preferred:**
```swift
vardiameter:Double
{
get
{
returnradius*2
}
}
```
### Final
Marking classes or members as `final` in tutorials can distract from the main topic and is not required. Nevertheless, use of `final` can sometimes clarify your intent and is worth the cost. In the below example, `Box` has a particular purpose and customization in a derived class is not intended. Marking it `final` makes that clear.
```swift
// Turn any generic type into a reference type using this Box class.
finalclassBox<T>
{
letvalue:T
init(_value:T)
{
self.value=value
}
}
```
## Function Declarations
Keep short function declarations on one line excluding the opening brace:
```swift
funcreticulateSplines(spline:[Double])->Bool
{
// reticulate code goes here
}
```
For functions with long signatures, add line breaks at appropriate points and add an extra indent on subsequent lines. Generally you should avoid such signatures.
Use trailing closure syntax only if there's a single closure expression parameter at the end of the argument list. Give the closure parameters descriptive names. Keep opening brace at the same line.
**Preferred:**
```swift
UIView.animate(withDuration:1.0){
self.myView.alpha=0
}
UIView.animate(withDuration:1.0,animations:{
self.myView.alpha=0
},completion:{finishedin
self.myView.removeFromSuperview()
})
```
**Not Preferred:**
```swift
UIView.animate(withDuration:1.0,animations:{
self.myView.alpha=0
})
UIView.animate(withDuration:1.0,animations:{
self.myView.alpha=0
}){fin
self.myView.removeFromSuperview()
}
```
For single-expression closures where the context is clear, use implicit returns:
```swift
attendeeList.sort{a,bin
a>b
}
```
Chained methods using trailing closures should be clear and easy to read in context. Decisions on spacing, line breaks, and when to use named versus anonymous arguments is left to the discretion of the author. Examples:
In Sprite Kit code, use `CGFloat` if it makes the code more succinct by avoiding too many conversions.
### Constants
Constants are defined using the `let` keyword, and variables with the `var` keyword. Always use `let` instead of `var` if the value of the variable will not change.
**Tip:** A good technique is to define everything using `let` and only change it to `var` if the compiler complains!
You can define constants on a type rather than on an instance of that type using type properties. To declare a type property as a constant simply use `static let`. Type properties declared in this way are generally preferred over global constants because they are easier to distinguish from instance properties. Example:
**Preferred:**
```swift
enumMath
{
staticlete=2.718281828459045235360287
staticletroot2=1.41421356237309504880168872
}
lethypotenuse=side*Math.root2
```
**Note:** The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace.
**Not Preferred:**
```swift
lete=2.718281828459045235360287// pollutes global namespace
letroot2=1.41421356237309504880168872
lethypotenuse=side*root2// what is root2?
```
### Static Methods and Variable Type Properties
Static methods and type properties work similarly to global functions and global variables and should be used sparingly. They are useful when functionality is scoped to a particular type or when Objective-C interoperability is required.
### Optionals
Declare variables and function return types as optional with `?` where a nil value is acceptable.
Use implicitly unwrapped types declared with `!` only for instance variables that you know will be initialized later before use, such as subviews that will be set up in `viewDidLoad`.
When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:
```swift
self.textContainer?.textLabel?.setNeedsDisplay()
```
Use optional binding when it's more convenient to unwrap once and perform multiple operations:
```swift
iflettextContainer=self.textContainer
{
// do many things with textContainer
}
```
When naming optional variables and properties, avoid naming them like `optionalString` or `maybeView` since their optional-ness is already in the type declaration.
For optional binding, shadow the original name when appropriate rather than using names like `unwrappedView` or `actualLabel`.
**Preferred:**
```swift
varsubview:UIView?
varvolume:Double?
// later on...
ifletsubview=subview,letvolume=volume
{
// do something with unwrapped subview and volume
}
```
**Not Preferred:**
```swift
varoptionalSubview:UIView?
varvolume:Double?
ifletunwrappedSubview=optionalSubview
{
ifletrealVolume=volume
{
// do something with unwrappedSubview and realVolume
}
}
```
### Lazy Initialization
Consider using lazy initialization for finer grain control over object lifetime. This is especially true for `UIViewController` that loads views lazily. You can either use a closure that is immediately called `{ }()` or call a private factory method. Example:
-`[unowned self]` is not required here. A retain cycle is not created.
- Location manager has a side-effect for popping up UI to ask the user for permission so fine grain control makes sense here.
### Type Inference
Prefer compact code and let the compiler infer the type for constants or variables of single instances. Type inference is also appropriate for small (non-empty) arrays and dictionaries. When required, specify the specific type such as `CGFloat` or `Int16`.
**Preferred:**
```swift
letmessage="Click the button"
letcurrentBounds=self.computeViewBounds()
varnames=["Mic","Sam","Christine"]
letmaximumWidth:CGFloat=106.5
```
**Not Preferred:**
```swift
letmessage:String="Click the button"
letcurrentBounds:CGRect=computeViewBounds()
letnames=[String]()
```
#### Type Annotation for Empty Arrays and Dictionaries
For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.)
**Preferred:**
```swift
varnames:[String]=[]
varlookup:[String:Int]=[:]
```
**Not Preferred:**
```swift
varnames=[String]()
varlookup=[String:Int]()
```
**NOTE**: Following this guideline means picking descriptive names is even more important than before.
### Syntactic Sugar
Prefer the shortcut versions of type declarations over the full generics syntax.
**Preferred:**
```swift
vardeviceModels:[String]
varemployees:[Int:String]
varfaxNumber:Int?
```
**Not Preferred:**
```swift
vardeviceModels:Array<String>
varemployees:Dictionary<Int,String>
varfaxNumber:Optional<Int>
```
## Functions vs Methods
Free functions, which aren't attached to a class or type, should be used sparingly. When possible, prefer to use a method instead of a free function. This aids in readability and discoverability.
Free functions are most appropriate when they aren't associated with any particular type or instance.
lettuples=zip(a,b)// feels natural as a free function (symmetry)
letvalue=max(x,y,z)// another free function that feels natural
```
## Memory Management
Code should not create reference cycles. Analyze your object graph and prevent strong cycles with `weak` and `unowned` references. Alternatively, use value types (`struct`, `enum`) to prevent cycles altogether.
### Extending object lifetime
Extend object lifetime using the `[weak self]` and `guard let strongSelf = self else { return }` idiom. `[weak self]` is preferred to `[unowned self]` where it is not immediately obvious that `self` outlives the closure. Explicitly extending lifetime is preferred to optional unwrapping.
Full access control annotation in tutorials can distract from the main topic and is not required. Using `private` and `fileprivate` appropriately, however, adds clarity and promotes encapsulation. Prefer `private` to `fileprivate` when possible. Using extensions may require you to use `fileprivate`.
Only explicitly use `open`, `public`, and `internal` when you require a full access control specification.
Use access control as the leading property specifier. The only things that should come before access control are the `static` specifier or attributes such as `@IBAction`, `@IBOutlet` and `@discardableResult`.
Prefer the `for-in` style of `for` loop over the `while-condition-increment` style.
**Preferred:**
```swift
for_in0..<3
{
print("Hello three times")
}
for(index,person)inattendeeList.enumerated()
{
print("\(person) is at position #\(index)")
}
forindexinstride(from:0,to:items.count,by:2)
{
print(index)
}
forindexin(0...3).reversed()
{
print(index)
}
```
**Not Preferred:**
```swift
vari=0
whilei<3
{
print("Hello three times")
i+=1
}
vari=0
whilei<attendeeList.count
{
letperson=attendeeList[i]
print("\(person) is at position #\(i)")
i+=1
}
```
## Golden Path
When coding with conditionals, the left-hand margin of the code should be the "golden" or "happy" path. That is, don't nest `if` statements. Multiple return statements are OK. The `guard` statement is built for this.
// use context and input to compute the frequencies
returnfrequencies
}
else
{
throwFFTError.noInputData
}
}
else
{
throwFFTError.noContext
}
}
```
When multiple optionals are unwrapped either with `guard` or `if let`, minimize nesting by using the compound version when possible. Example:
**Preferred:**
```swift
guardletnumber1=number1,
letnumber2=number2,
letnumber3=number3else
{
fatalError("impossible")
}
// do something with numbers
```
**Not Preferred:**
```swift
ifletnumber1=number1{
ifletnumber2=number2{
ifletnumber3=number3{
// do something with numbers
}else{
fatalError("impossible")
}
}else{
fatalError("impossible")
}
}else{
fatalError("impossible")
}
```
### Failing Guards
Guard statements are required to exit in some way. Generally, this should be simple one line statement such as `return`, `throw`, `break`, `continue`, and `fatalError()`. Large code blocks should be avoided. If cleanup code is required for multiple exit points, consider using a `defer` block to avoid cleanup code duplication.
## Semicolons
Swift does not require a semicolon after each statement in your code. They are only required if you wish to combine multiple statements on a single line.
Do not write multiple statements on a single line separated with semicolons.
**Preferred:**
```swift
letswift="not a scripting language"
```
**Not Preferred:**
```swift
letswift="not a scripting language";
```
## Parentheses
Parentheses around conditionals are not required and should be omitted.
**Preferred:**
```swift
ifname=="Hello"
{
print("World")
}
```
**Not Preferred:**
```swift
if(name=="Hello")
{
print("World")
}
```
In larger expressions, optional parentheses can sometimes make code read more clearly.