Swift style guide
Spaces
- Use tabs, not spaces
- End files with a newline.
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 true { // Do something } else { // Do something else }
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:
class TestDatabase: Database {
var data: [String: CGFloat] = ["A": 1.2, "B": 3.2]
}
Naming
Use descriptive names with camel case for classes, methods, variables, etc. Type names (classes, structures, enumerations and protocols) should be capitalized, while method names and variables should start with a lower case letter.
When dealing with an acronym or other name that is usually written in all caps, actually use all caps in any names that use this in code. The exception is if this word is at the start of a name that needs to start with lowercase - in this case, use all lowercase for the acronym.
Preferred:
// "HTML" is at the start of a constant variable name, so we use lowercase "html"
let htmlBodyContent: String = "<p>Hello, World!</p>"
// Prefer using ID to Id
let profileID: Int = 1
// Prefer URLFinder to UrlFinder
class URLFinder {
/* ... */
}
- For functions and init methods, prefer named parameters for all arguments
func dateFromString(dateString: String) -> NSDate
func convertPointAt(column column: Int, row: Int) -> CGPoint
func timedAction(afterDelay delay: NSTimeInterval, perform action: SKAction) -> SKAction!
For methods, we will follow the standard Apple convention of referring to the first parameter in the method name:
class Counter {
func combineWith(otherCounter: Counter, options: Dictionary?) { ... }
func incrementBy(amount: Int) { ... }
}
Parentheses
Parentheses around conditionals are not required.
if name == "Hello" {
print("World")
}
Comma
There should be no space before and one space after comma
Empty Count
Prefer checking isEmpty
over comparing count
to zero.
Coding Style
Prefer let over var