Home

Awesome

Coursera Swift coding guidelines

General

Variables or constants

Preferred

let course = "Course"
var courseTitle: String

Not preferred

let course: String = "Course"

Ordering instance variables

Order the instance variables in the class, with this order:

If-Else

if let name = optionalName {
  	greeting = "Hello, \(name)"
} else {
    greeting = "Bye"
}

Optionals

Use if let syntax if the unwrapping involves more than 1 statement or when the optional is to be used as a conditional.

Use ? in other cases.

Example:

if let unwrapped = optional {
	  unwrapped statement 1;
	  unwrapped statement 2;
}

optional?.optionalFunction()  // evaluates to nil if optional is not present

Use optional chaining when you need to go through a series of optionals.

Example:

if let validCorgis = coursera.mobileTeam?.coreTeam?.corgis {
  	validCorgis
}

Classes

Functions

Example:

func findIndexOfString(#inputString: String, #array: [String]) -> (index: Int?, name: String?) {
    for (index, value) in enumerate(array) {
        if (value == string) {
            return (index, string)
        }
    }
    return (nil, nil)
}

KVO

Example:

import Foundation
class ClassB: NSObject {
    var someProperty: Int = 0
}

private var NewClassKVOContext = "NewClassKVOContext"

class NewClass: NSObject {
    var classB: ClassB

    override init() {
        classB = ClassB()
        super.init()
        classB.addObserver(self, forKeyPath: "someProperty", options: .Initial | .New, context: &newClassKVOContext)
    }

    // MARK: KVO Methods

    override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafeMutablePointer<Void>) {
        if context != &newClassKVOContext {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
						return
        }

        switch keyPath {
        case "someProperty":
            somePropertyChanged(change[NSKeyValueChangeNewKey])
        default:
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }

    func somePropertyChanged(someProperty: AnyObject?) {
        if let validSomeProperty = someProperty as? Bool {
            // Do something
        }
    }

    // MARK: Deinit

    deinit {
        classB.removeObserver(self, forKeyPath: "someProperty", context: &newClassKVOContext)
    }
}