Swift Language Style Conventions Clear Usage

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Avoid Ambiguity

The name of classes, structures, functions and variables should avoid ambiguity.

Example:

extension List {
    public mutating func remove(at position: Index) -> Element {
        // implementation
    }
}

The function call to this function will then look like this:

list.remove(at: 42)

This way, ambiguity is avoided. If the function call would be just list.remove(42) it would be unclear, if an Element equal to 42 would be removed or if the Element at Index 42 would be removed.


Avoid Redundancy

The name of functions should not contain redundant information.

A bad example would be:

extension List {
    public mutating func removeElement(element: Element) -> Element? {
        // implementation
    }
}

A call to the function may look like list.removeElement(someObject). The variable someObject already indicates, that an Element is removed. It would be better for the function signature to look like this:

extension List {
    public mutating func remove(_ member: Element) -> Element? {
        // implementation
    }
}

The call to this function looks like this: list.remove(someObject).


Naming variables according to their role

Variables should be named by their role (e.g. supplier, greeting) instead of their type (e.g. factory, string, etc..)

High coupling between Protocol Name and Variable Names

If the name of the type describes its role in most cases (e.g. Iterator), the type should be named with the suffix `Type`. (e.g. IteratorType)

Provide additional details when using weakly typed parameters

If the type of an object does not indicate its usage in a function call clearly, the function should be named with a preceding noun for every weakly typed parameter, describing its usage.
Example:
func addObserver(_ observer: NSObject, forKeyPath path: String)

to which a call would look like `object.addObserver(self, forKeyPath: path)

instead of

func add(_ observer: NSObject, for keyPath: String)

to which a call would look like object.add(self, for: path)



Got any Swift Language Question?