This style guide is a work in progress aimed at readability, simplicity, and conciseness. Based on the Official raywenderlich.com Swift Style Guide.
- Spacing
- Comments
- Numbers
- Conditionals
- Naming
- Semicolons
- Classes and Structures
- Use of Self
- Function Declarations
- Closures
- Types
- Control Flow
- Credits
- Indent using 4 spaces rather than tabs. 4 spaces helps keep indentation levels very clear. Be sure to set this preference in Xcode.
- Method braces and other braces (
if
/else
/switch
/while
etc.) always open on the same line as the statement but close on a new line.
Preferred:
if user.isHappy {
//Do something
} else {
//Do something else
}
Not Preferred:
if user.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.
Any comma separated list should have a space after each comma.
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
func describePoint(x: Int, y: Int) -> String {
return "I am a circle at (\(x), \(y)) with an area of \(x * y)"
}
let array = ["one", "two", "three"]
Binary and Ternary operators should include spaces between the operator(s) and targets while unary operators should not:
let four = (1 + 1) * 2
let mood = isSunnyOut ? "happy" : "foul"
let i = 0
let plusOne = ++i
- Note: An exception is made for the range operators
...
and..<
which should not have spaces between the operator and targets.
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.
Very large numbers should use an underscore after every third power for visual clarity:
let fileSize = 100_000_000
Conditionals should not use parenthesis unless needed to group statements:
Preferred:
let name = "world"
if name == "world" {
println("hello, world")
}
Not Preferred:
let name = "world"
if (name == "world") {
println("hello, world")
}
Use descriptive names with camel case for classes, methods, variables, etc. Class names and constants in module scope should be capitalized, while method names and variables should start with a lower case letter.
Preferred:
let MaximumWidgetCount = 100
class WidgetContainer {
var widgetButton: UIButton
let widgetHeightPercentage = 0.85
}
Not Preferred:
let MAX_WIDGET_COUNT = 100
class app_widgetContainer {
var wBut: UIButton
let wHeightPct = 0.85
}
Abbreviations in camelCase names should be all capitalized unless they are the first or only word of that name in which case they should be lowercase.
Preferred:
let url = NSURL(string: "http://foo.bar")
let absoluteURL = url?.absoluteURL
Not Preferred:
let URL = NSURL(string: "http://foo.bar")
let absoluteUrl = url?.absoluteURL
For enumerated types, as per Apple's recommendation, the type name should be in the singular.
Preferred:
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
Not Preferred:
enum Planets {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
For functions and init methods, prefer named parameters for all arguments unless the context is very clear. Include external parameter names if it makes function calls more readable.
func dateFromString(dateString: NSString) -> NSDate
func convertPointAt(#column: Int, #row: Int) -> CGPoint
func timedAction(#delay: NSTimeInterval, perform action: SKAction) -> SKAction!
// would be called like this:
dateFromString("2014-03-14")
convertPointAt(column: 42, row: 13)
timedAction(delay: 1.0, perform: someOtherAction)
For methods, follow the standard Apple convention of referring to the first parameter in the method name:
class Guideline {
func combineWithString(incoming: String, options: Dictionary?) { ... }
func upvoteBy(amount: Int) { ... }
}
Swift types are all automatically namespaced by the module that contains them. As a result, prefixes are not required in order to minimize naming collisions. If two names from different modules collide you can disambiguate by prefixing the type name with the module name:
import MyModule
var myClass = MyModule.MyClass()
You should not add prefixes to your Swift types.
If you need to expose a Swift type for use within Objective-C you can provide a suitable prefix (following our Objective-C style guide) as follows:
@objc (RWTChicken) class Chicken {
...
}
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.
The only exception to this rule is the for-conditional-increment
construct, which requires semicolons. However, alternative for-in
constructs should be used where possible.
Preferred:
var swift = "not a scripting language"
Not Preferred:
var swift = "not a scripting language";
NOTE: Swift is very different to JavaScript, where omitting semicolons is generally considered unsafe
Here's an example of a well-styled class definition:
class Circle: Shape {
var x: Int, y: Int
var radius: Double
var diameter: Double {
get {
return radius * 2
}
set {
radius = newValue / 2
}
}
init(x: Int, y: Int, radius: Double) {
self.x = x
self.y = y
self.radius = radius
}
convenience init(x: Int, y: Int, diameter: Double) {
init(x: x, y: y, radius: diameter / 2)
}
func describe() -> String {
return "I am a circle at (\(x), \(y)) with an area of \(computeArea())"
}
func computeArea() -> Double {
return M_PI * radius * radius
}
}
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
, andCircle: Shape
. - Indent getter and setter definitions and property observers.
- Define multiple variables and structures on a single line if they share a common purpose / context.
You should use self
to access an object's properties and invoke its methods only when necessary. Let Xcode color code the properties for you to differentiate the scope of the variable. (Note: Xcode does not color code functions/methods to differentiate them so being overly verbose and using self to refer to methods should perhaps be revisited.)
class BoardLocation {
let row: Int, column: Int
init(row: Int, column: Int) {
self.row = row
self.column = column
}
func describe() -> String {
return "Row \(row), column \(column)"
}
}
Keep short function declarations on one line including the opening brace:
func reticulateSplines(spline: [Double]) -> Bool {
// reticulate code goes here
}
For functions with long signatures, add line breaks at appropriate points, add an extra indent on subsequent lines, and move the opening brace to its own line:
func reticulateSplines(spline: [Double], adjustmentFactor: Double,
translateConstant: Int, comment: String) -> Bool
{
// reticulate code goes here
}
Don't specify the output type as Void. Simply leave it out.
Preferred:
func reticulateSplines(spline: [Double]) {
// reticulate code goes here
}
Not Preferred:
func reticulateSplines(spline: [Double]) -> Void {
// reticulate code goes here
}
func reticulateSplines(spline: [Double]) -> () {
// reticulate code goes here
}
Use trailing closure syntax wherever possible. In all cases, give the closure parameters descriptive names:
return SKAction.customActionWithDuration(effect.duration) { node, elapsedTime in
// more code goes here
}
For single-expression closures where the context is clear, use implicit returns:
attendeeList.sort { a, b in
a > b
}
For very simple closures, you should put them on a single line without naming the parameters. You should include a space after the opening curly brace and before the closing brace:
attendeeList.sort { $0 > $1 }
Always use Swift's native types when available. Swift offers bridging to Objective-C so you can still use the full set of methods as needed.
Preferred:
let width = 120.0 //Double
let widthString = width.bridgeToObjectiveC().stringValue //String
Not Preferred:
let width: NSNumber = 120.0 //NSNumber
let widthString: NSString = width.stringValue //NSString
In Sprite Kit code, use CGFloat
if it makes the code more succinct by avoiding too many conversions.
Constants are defined using the let
keyword, and variables with the var
keyword. Any value which is a constant must be defined appropriately, using the let
keyword. As a result, you will likely find yourself using let
far more than var
.
Tip: One technique that might help meet this standard is to define everything as a constant and only change it to a variable when the compiler complains!
Declare variables and function return types as optional with ?
where a nil value is acceptable.
Avoid using !
whereever possible. Instead try to use if let
to create a non-optional. If you're using !
it should be in a conditional that ensures the variable is non-nil.
When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:
myOptional?.anotherOne?.optionalView?.setNeedsDisplay()
Use optional binding when it's more convenient to unwrap once and perform multiple operations or if you need to do any assignment:
if let view = self.optionalView {
// do many things with view
}
Tuples are very useful for returning multiple values back from a function. When declaring variables for those tuple values, favor naming each variable in the tuple rather than the tuple itself.
Preferred:
let (object, error) = createObject()
Not Preferred:
let tuple = createObject()
let object = tuple.object
let error = tuple.error
A common use for returning tuples is for factory methods that return one or more optional values and an optional error in case the thing(s) are not created properly. When doing so, the error should be the last value in the tuple.
Preferred:
func createObject() -> (object: NSObject?, error: NSError?)
Not Preferred:
func createObject() -> (error: NSError?, object: NSObject?)
The Swift compiler is able to infer the type of variables and constants. You can provide an explicit type via a type alias (which is indicated by the type after the colon), but in the majority of cases this is not necessary.
Prefer compact code and let the compiler infer the type for a constant or variable.
Preferred:
let message = "Click the button"
var currentBounds = computeViewBounds()
Not Preferred:
let message: String = "Click the button"
var currentBounds: CGRect = computeViewBounds()
NOTE: Following this guideline means picking descriptive names is even more important than before.
Prefer the shortcut versions of type declarations over the full generics syntax.
Preferred:
var deviceModels: [String]
var employees: [Int: String]
var faxNumber: Int?
Not Preferred:
var deviceModels: Array<String>
var employees: Dictionary<Int, String>
var faxNumber: Optional<Int>
Prefer the shortcut versions of enum values.
Preferred:
view.autoresizingMask = .FlexibleWidth | .FlexibleHeight
Not Preferred:
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
Prefer the for-in
style of for
loop over the for-condition-increment
style.
Preferred:
for _ in 0..<3 {
println("Hello three times")
}
for person in attendeeList {
// do something
}
Not Preferred:
for var i = 0; i < 3; i++ {
println("Hello three times")
}
for var i = 0; i < attendeeList.count; i++ {
let person = attendeeList[i]
// do something
}
This style guide has been assembled by:
And is derived from a collaborative effort from the most stylish raywenderlich.com team members:
- Soheil Moayedi Azarpour
- Scott Berrevoets
- Eric Cerney
- Sam Davies
- Evan Dekhayser
- Jean-Pierre Distler
- Colin Eberhardt
- Greg Heo
- Matthijs Hollemans
- Erik Kerber
- Christopher LaPollo
- Andy Pereira
- Ryan Nystrom
- Cesare Rocchi
- Ellen Shapiro
- Marin Todorov
- Chris Wagner
- Ray Wenderlich
- Jack Wu
Hat tip to Nicholas Waynik and the Objective-C Style Guide team!
We also drew inspiration from Apple’s reference material on Swift: