Skip to content

Instantly share code, notes, and snippets.

@Infinity-James
Last active May 6, 2016 08:23
Show Gist options
  • Save Infinity-James/0f871c9257695caa28e6 to your computer and use it in GitHub Desktop.
Save Infinity-James/0f871c9257695caa28e6 to your computer and use it in GitHub Desktop.
Office Serve Swift Style Guide

Naming

Use descriptive names with camel case for classes, methods, variables, etc. Class names should be capitalized, while method names and variables should start with a lower case letter.

Preferred:
private let maximumFoodProducts = 100

class FoodProductDetailView
{
    var addToBasketButton: UIButton
    let imageViewDimension = 256.0
}
Discouraged:
let MAX_FOOD_COUNT = 100

class app_foodDetailView
{
    var addBut: UIButton
    let imgHt = 256.0
}

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: String) -> 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) { ... }
}

Enumerations

Use UpperCamelCase for enumeration values:

enum Food
{
    case Vegetable
    case Fruit
    case Legume
    case Grain
    case Meat
    case Fish
    case MeatSubstitute
}

Class Prefixes

Swift types are automatically namespaced by the module that contains them and you should not add a class prefix. If two names from different modules collide you can disambiguate by prefixing the type name with the module name.

import SomeModule

let myClass = MyModule.UsefulClass()

Spacing

  • Indent using 4 spaces rather than tabs. 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.

  • Tip: You can re-indent by selecting some code (or ⌘A to select all) and then Control-I (or Editor\Structure\Re-Indent in the menu).

Preferred:
if james.isAwesome {
    // Do something
} else {
    // Do something else
}
Discouraged:
if james.isAwesome
{
    // 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.

Classes and Structures

Which one to use?

Remember, structs have value semantics. 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. 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:

class Alien: Being {
    var arms: Int, legs: Int
    var homePlanet: String
    var limbs: Int {
        get {
            return arms + legs
        }
        set {
            arms = Int(newValue / 2)
            legs = newValue - arms
        }
    }

    init(name: String, arms: Int, legs: Int, homePlanet: String) {
        self.arms = arms
        self.legs = legs
        self.homePlanet = homePlanet

        super.init(name: name)
    }

    convenience init(name: String, arms: Int, legs: Int) {
        self.init(name: name, arms: arms, legs: legs, homePlanet: "Unknown")
    }

    func describe() -> String {
        return "Alien: \(greeting())"
    }

    override func greeting() -> Double {
        return "I am \(name) from \(homePanet), and I come in peace."
    }

    private func wantsToWipeOutHumans() -> Bool {
        if homePlanet == "Mars" {
            return true
        } else {
            return false
        }
    }
}

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. arms: Int, and Alien: Being.
  • Define multiple variables and structures on a single line if they share a common purpose / context, e.g. var arms: Int, legs: Int
  • 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.

Use of Self

For conciseness, avoid using self since Swift does not require it to access an object's properties or invoke its methods.

Use self when required to differentiate between property names and arguments in initializers, and when referencing properties in closure expressions (as required by the compiler):

struct Framework {
    let bugs: Int, crashes: Int, linesOfCode: Int
    let compileTime: Double

    init(bugs: Int, crashes: Int, linesOfCode: Int) {
        self.bugs = bugs
        self.crashes = crashes
        self.linesOfCode = linesOfCode

        compileTime = self.linesOfCode * 0.002

        let closure = {
            println(self.compileTime)
        }
  }
}

Protocol Conformance

When adding protocol conformance to a class, prefer adding a separate class 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.

Also, don't forget the // MARK: comment to keep things well-organized!

Preferred:
class MyViewController: UIViewController {
  // class stuff here
}

// MARK: UITableViewDataSource
extension MyViewController: UITableViewDataSource {
  // table view data source methods
}

// MARK: UIScrollViewDelegate
extension MyViewController: UIScrollViewDelegate {
  // scroll view delegate methods
}
Discouraged:
class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate {
  // all 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:
var diameter: Double {
    return radius * 2
}
Discouraged:
var diameter: Double {
    get {
        return radius * 2
    }
}

Function Declarations

Keep short function declarations on one line including the opening brace:

func buildVehicle(wheels: Int) -> Vehicle {
    //  build a vehicle
}

For functions with long signatures, add line breaks at appropriate points and add an extra indent on subsequent lines:

func buildVehicle(wheels: Int, engine: Bool,
    seats: Int, vehicleName: String) -> Vehicle {
  // build a vehicle
}

Closure Expressions

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.

Preferred:
UIView.animateWithDuration(1.0) {
  self.myView.alpha = 0
}

UIView.animateWithDuration(1.0,
  animations: {
    self.myView.alpha = 0
  },
  completion: { finished in
    self.myView.removeFromSuperview()
  }
)
Discouraged:
UIView.animateWithDuration(1.0, animations: {
  self.myView.alpha = 0
})

UIView.animateWithDuration(1.0,
  animations: {
    self.myView.alpha = 0
  }) { f in
    self.myView.removeFromSuperview()
}

For single-expression closures where the context is clear, use implicit returns:

publications.sort { a, b in
  a > b
}

Where the closure fits nicely on a single line, use the short hand for the arguments ($0, $1, etc.):

publications.sort { $0 > $1 }

Closure Safety

Reference cycles are still a very real danger in Swift. When assigning a closure to a property held by an instance of a class, any use of self within that closure has the ability to cause issues due to two properties holding on strongly to one another, and this would result in neither being released.

To avoid this situation we use the weak keyword to capture self weakly within the closure, and avoid the reference cycle.

Preferred
completionHandler = { [weak self] success in
    guard let strongSelf = self else { return }

    if (success) {
        strongSelf.publicationDownloaded()
    }
}
Discouraged
completionHandler = { success in
    if (success) {
        self.publicationDownloaded()
    }
}

Weak is Not Enough

Simply capturing self weakly is not enough to avoid unexpected behaviour. Before using self in a closure you must unwrap it and the guidance here is to do so using the guard statement. To look at why it must be unwrapped, let's see an example where self is used safely, but not unwrapped up front:

completionHandler = { [weak self] success in
    if (success) {
        self?.cacheFoodProductImages()
        
        self?.clearCache()
    }
}

This would appear to be fine, but consider what happens if between the call to cacheFoodProductImages() and clearCache() if self was deallocated and nilified. We would be left in an undefined state where we never got to clear the cache, and this will undoubtedly result in undefined behaviour.

Solution:
completionHandler = { [weak self] success in
    guard let strongSelf = self where success else { return }

        strongSelf.cacheFoodProductImages()
        
        strongSelf.clearCache()
}

Types

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 as NSNumber).stringValue    // String
Discouraged:
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

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.

Optionals

Declare variables and function return types as optional with ? where a nil value is acceptable.

Avoid implicitly unwrapped types declared with !, using only where required for @IBOutlet instance variables that you know will be initialized later before use.

When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:

self.textContainer?.textLabel?.setNeedsDisplay()

Use optional binding when it's more convenient to unwrap once and perform multiple operations:

if let textContainer = 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:
var subview: UIView?
var volume: Double?

// later on...
if let subview = subview, volume = volume {
  // do something with unwrapped subview and volume
}
Discouraged:
var optionalSubview: UIView?
var volume: Double?

if let unwrappedSubview = optionalSubview {
  if let realVolume = volume {
    // do something with unwrappedSubview and realVolume
  }
}

Struct Initializers

Use the native Swift struct initializers rather than the legacy CGGeometry constructors.

Preferred:
let bounds = CGRect(x: 40, y: 20, width: 120, height: 80)
let centerPoint = CGPoint(x: 96, y: 42)
Discouraged:
let bounds = CGRectMake(40, 20, 120, 80)
let centerPoint = CGPointMake(96, 42)

Prefer the struct-scope constants CGRect.infiniteRect, CGRect.nullRect, etc. over global constants CGRectInfinite, CGRectNull, etc. For existing variables, you can use the shorter .zeroRect.

Type Inference

Prefer compact code and let the compiler infer the type for a constant or variable, unless you need a specific type other than the default such as CGFloat or Int16.

Preferred:
let message = "Click the button"
let currentBounds = computeViewBounds()
var names = [String]()
let maximumWidth: CGFloat = 106.5
Discouraged:
let message: String = "Click the button"
let currentBounds: CGRect = computeViewBounds()
var names: [String] = []

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:
var deviceModels: [String]
var employees: [Int: String]
var faxNumber: Int?
Discouraged:
var deviceModels: Array<String>
var employees: Dictionary<Int, String>
var faxNumber: Optional<Int>

Control Flow

The for-in style of for loop should always be used over the for-condition-increment style. With Swift 3.0 the old C-style loops will no longer build.

Preferred:
for _ in 0..<3 {
  println("Hello three times")
}

for (index, publication) in enumerate(publications) {
  println("\(publication) is at position #\(index)")
}
Prohibited:
for var i = 0; i < 3; i++ {
  println("Hello three times")
}

for var i = 0; i < publications.count; i++ {
  let publication = publications[i]
  println("\(publication) is at position #\(i)")
}

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.

The only exception to this rule would be the for-conditional-increment construct, which requires semicolons. However, the for-in constructs should be used where in place of these anyway.

Preferred:
let swift = "not a scripting language"
Discouraged:
let swift = "not a scripting language";

Note: Swift is very different to JavaScript, where omitting semicolons is generally considered unsafe.

Language

Use US English spelling to match Apple's API.

Preferred:
let color = "red"
Discouraged:
let colour = "red"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment