Swift Language Fluent Usage


Example

Using natural language

Functions calls should be close to natural English language.

Example:

list.insert(element, at: index) 

instead of

list.insert(element, position: index)

Naming Factory Methods

Factory methods should begin with the prefix `make`.

Example:

factory.makeObject()

Naming Parameters in Initializers and Factory Methods

The name of the first argument should not be involved in naming a factory method or initializer.

Example:

factory.makeObject(key: value)

Instead of:

factory.makeObject(havingProperty: value)

Naming according to side effects

  • Functions with side effects (mutating functions) should be named using verbs or nouns prefixed with form- .
  • Functions without side effects (nonmutating functions) should be named using nouns or verbs with the suffix -ing or -ed.
Example: Mutating functions:
print(value)
array.sort()                 // in place sorting
list.add(value)              // mutates list
set.formUnion(anotherSet)    // set is now the union of set and anotherSet

Nonmutating functions:

let sortedArray = array.sorted()     // out of place sorting
let union = set.union(anotherSet)    // union is now the union of set and another set

Boolean functions or variables

Statements involving booleans should read as assertions.

Example:

set.isEmpty
line.intersects(anotherLine)

Naming Protocols

  • Protocols describing what something is should be named using nouns.
  • Protocols describing capabilities should have -able, -ible or -ing as suffix.
Example:
Collection        // describes that something is a collection
ProgressReporting // describes that something has the capability of reporting progress
Equatable         // describes that something has the capability of being equal to something

Types and Properties

Types, variables and properties should read as nouns.

Example:

let factory = ...
let list = [1, 2, 3, 4]