jduthon / SwiftGuideline

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Poisson's Swift Style Guide

My Swift guideline is extremely inspired by Hyperoslo's Guideline and Raywenderlich's Guideline
Thanks !

I have made little personal adjustments and this repository allows me to share them.

Table of Contents

Naming

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 begin with a lower case letter.

Preferred:

let MaximumWidgetCount = 100 

class WidgetContainer {
  var widgetButton: UIButton
  let widgetHeightPercentage = 0.85
}

Disfavored :

let MAX_WIDGET_COUNT = 100

class app_widgetContainer {
  var wBut: UIButton
  let wHeightPct = 0.85
}
  • Variables

Classes or structure variables should start with a lower case letter. Scope variables should be prefixed by 'l'. Parameters variables prefixed by 'p'.

Preferred:

class HomeViewController {
	var nameOfPerson:String?
  let weapons = [Weapon]()
  
  func haveName() -> Bool {
	var lRet = false
	
  if let lName = self.nameOfPerson {
	lRet = true
  }
  return lRet
}

Disvafored:

class HomeViewController {
	var nameOfPerson:String?
  let weapons = [Weapon]()
  
  func oneUselessFunction() -> Bool {
	var isName = false
	
  if let name = self.nameOfPerson {
	isName = true
  }
  return isName
}
  • Functions

For functions and init methods, prefer named parameters for all arguments unless the context is very clear. Include external parameters 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) { ... }
}

When referring to functions in prose include the required parameter name from the caller's perspective. If the context is clear and the exact signature is not important, you can use the method name alone.

Call convertPointAt(column:row:) from your own init implementation.

If you implement timedAction, remember to provide an appropriate delay value.

You should not call the data source method tableView(_:cellForRowAtIndexPath:) directly.

When in doubt, have a look at how Xcode lists methods in the jump bar – our style here matches their.

Methods in Xcode jump bar

Class Prefixes

Swift types are all automatically namespaced by the module which 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 lClass = 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 {
   ...
}

Spacing and Indentation

  • Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. This should be configured in the project settings.

    Xcode indent settings

  • Method braces and other braces (if/else/switch/while etc.) should always be opened at the statement's line but closed after line break.

  • 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). Some of the Xcode template code have 4-space tabs hard coded, so this is a good way to fix it.

Preferred:

if user.isHappy {
  // Do something
} else {
  // Do something else
}

Disfavored:

if user.isHappy
{
    // Do something
}
else {
    // Do something else
}
  • There should be exactly one blank line between methods to aid with 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 Structs

Unless you require functionality that can only be provided by a class, implement a struct instead.

Additional capabilities of classes:

  • Inheritance: Enable one class to inherit the characteristics of another
  • Type casting: Enable you to check and interpret the type of a class instance at runtime
  • Deinitializers: Enable an instance of a class to free up any resources it has assigned
  • Reference counting: Allow more than one reference to a class instance
  • Compatibility: Classes are available from Objective-C

Use of Self

Use self only when required, for example:

  • When using optional binding with optional properties

Preferred:

if let lTextContainer = textContainer {
  // do many things with textContainer
}

Disfavored:

if let lTextContainer = self.textContainer {
  // do many things with textContainer
}
if let maybeThisCouldBeTextContainer = textContainer {
  // do many things with maybeThisCouldBeTextContainer
}
  • To differentiate between property names and arguments in initializers
  • When referencing properties in closure expressions
init(row: Int, column: Int) {
  self.row = row
  self.column = column

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

tl;dr Only use self when the language requires it.

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
}

Disfavored:

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.0
}

Disfavored:

var diameter: Double {
  get {
    return radius * 2.0
  }
}

Example definition

Here is 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.0
    }
    set {
      radius = newValue / 2.0
    }
  }

  init(x: Int, y: Int, radius: Double) {
    self.x = x
    self.y = y
    self.radius = radius
  }

  convenience init(x: Int, y: Int, diameter: Double) {
    self.init(x: x, y: y, radius: diameter / 2.0)
  }

  func describe() -> String {
    return "I am a circle at \(centerString()) with an area of \(computeArea())"
  }

  override func computeArea() -> Double {
    return M_PI * radius * radius
  }

  private func centerString() -> String {
    return "(\(x),\(y))"
  }
}

The example above demonstrates the following style guidelines:

  • The correct spacing for variable assignations is with a space after and before the equals mark =, e.g. x = 3
  • Attributes in method signature have the : next to the name, e.g init(x: Int, y: Int) same with class inheritance and when using type inference
  • 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

Function Rules

Function Declarations

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

func reticulateSplines(spline: [Double]) -> Bool {
  // reticulate code goes here
}

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

func reticulateSplines(spline: [Double], adjustmentFactor: Double,
    translateConstant: Int, comment: String) -> Bool {
  // reticulate code goes here
}

Function organisation

Always declare all your local variables at the beginning of your function and make a carriage return between local variables and the rest of your code:

Preferred:

func makeSomething() {
	let lVariable = ""
	let lIsSet = false
	let lLastInformation:AnyObject?
	
	//DoSomething
}

Disfavored:

func makeSomething() {
	let lVariable = ""	
	//DoSomething
	let lIsSet = false
	let lLastInformation:AnyObject?
}

Function Return

Always use only one return in your functions. This rule keeps functions clean, fast readable and easy to debug ! (trust me ^^)

Preferred:

func indexOfViewController(viewController:  UIViewController) -> Int {
	var lRet = NSNotFound 
	
   if let lIndex = self.listController.indexOf(viewController) {
      lRet = lIndex
    } 
    return lRet
  }

Disfavored:

func indexOfViewController(viewController:  UIViewController) -> Int {
  if let lIndex = self.listController.indexOf(viewController) {
      return lIndex
    } else {
      return NSNotFound
    }
}

Closure Expressions

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
}

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

Disfavored:

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. Any value that 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!

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:

textContainer?.textLabel?.setNeedsDisplay()

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

if let lTextContainer = textContainer {
  // do many things with textContainer
}

Use guard unwrapping if the object is required for continuing the operation. guard is prefered when doing early return inside a function.

guard let lRequiredObject = object else { return }

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?

// later on...
if let lSubview = subview {
  // do something with unwrapped subview
}

Disfavored:

var optionalSubview: UIView?

if let unwrappedSubview = optionalSubview {
  // do something with unwrappedSubview
}

Struct Initializers

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

Preferred:

let bounds = CGRect(x: 40.0, y: 20.0, width: 120.0, height: 80.0)
var centerPoint = CGPoint(x: 96.0, y: 42.0)

Disfavored:

let bounds = CGRectMake(40.0, 20.0, 120.0, 80.0)
var centerPoint = CGPointMake(96.0, 42.0)

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

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 general this is not necessary.

Prefer compact code and let the compiler infer the type of constant or variable.

Preferred:

let message = "Click the button"
var currentBounds = computeViewBounds()

Disfavored:

let message: String = "Click the button"
var currentBounds: CGRect = computeViewBounds()

NOTE: Following this guideline means choosing descriptive names is even more important than before.

Syntactic Sugar

Prefer the shortcut version of type declarations over the full generics syntax.

Preferred:

var deviceModels: [String]
var employees: [Int: String]
var faxNumber: Int?

Disfavored:

var deviceModels: Array<String>
var employees: Dictionary<Int, String>
var faxNumber: Optional<Int>

Control Flow

forEach

Prefer forEach over for-in when applicable.

Preferred:

Use named parameters when the object is being referenced more than once.

attendeeList.forEach { pAttendee in 
  print("\(pAttendee.name) is attending with \(pAttendee.guests.count) guests.") 
}

Anonymous parameters

[subview, anotherSubview].forEach { view.addSubview($0) }

There are some disadvantages of using forEach over for-in which you should probably be aware of.

/// - Note: You cannot use the `break` or `continue` statement to exit the
///   current call of the `body` closure or skip subsequent calls.
/// - Note: Using the `return` statement in the `body` closure will only
///   exit from the current call to `body`, not any outer scope, and won't
///   skip subsequent calls.

Reference: apple/swift/stdlib/public/core/Sequence.swift

So if the operation demands more control, then use for-in.

for-in

Prefer the for-in style of for loop over the for-condition-increment style.

Preferred:

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

for (lIndex, lPerson) in enumerate(attendeeList) {
  println("\(lPerson) is at position #\(lIndex)")
}

Disfavored:

for var i = 0; i < 3; i++ {
  println("Hello three times")
}

for var i = 0; i < attendeeList.count; i++ {
  let person = attendeeList[i]
  println("\(person) 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 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"

Disfavored:

var swift = "not a scripting language";

NOTE: Swift is very different compared to JavaScript, where omitting semicolons is generally considered unsafe

Ressource code

In Swift it's a good practice to use struct for accessing elements of asset catalogs, storyboards, custom colors and fonts. It helps to avoid the error-prone practice of hardcoding strings into your code.

struct ColorList {
  static let someColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 0.8)
}

TODO

  • Talk about Nil Coalescing Operator
  • Check example

About