swift-guide

Naming

In general, follow the official guidelines.

Conventions

Naming a file

Naming a class, a struct or a protocol

Naming a class or a protocol available in Objective-C

Provide a pre-fixed Objective-C name before the class or protocol definition.

Example

@objc class Event {
    // bad: exported to Objective-C as class Event without a prefix
}

@objc(XYZEvent)
class Event {
    // good
}

Naming a protocol

Example

protocol IFooEventHandler {
    // bad: the "I" prefix is not necessary
}

protocol FooEventHandler {
    // bad: "er" is not a good suffix for a protocol
}

protocol FooEventHandling {
    // good
}

Naming a delegate method

The first parameter should always be the item that is calling the delegate method.

Rationale

Dedicating the first parameter to be the item that is calling the delegate method follows Apple’s API design pattern.

Example:

// really bad: there's no parameter for the item that is calling the delegate method.
func didDeleteDraft()

// bad: the delegate method caller is not the first parameter
func didDeleteDraft(draft: Draft, draftManager: DraftManager)

// good
func draftManager(_ manager: DraftManager, didDeleteDraft draft: Draft)

Naming an event handler method

An event handler method should be name following this pattern:

handle<EventSource>[<Action>]

where EventSource is the UIControl or NSNotification which fired the event and Action is a past-tense verb described what happened.

Example:

// bad: unclear what was the event source
// An NSNotification handler (EventSource=KeyboardDidShowNotification, Action=NULL)
didShowKeyboardNotification()

// good: the event source is clearly part of the function name
// An NSNotification handler (EventSource=KeyboardDidShowNotification, Action=NULL)
handleKeyboardDidShowNotification()

// bad: unclear that this function is handling the notification
// A UIButton handler (EventSource=ConfirmButton, Action=Tapped)
confirmButtonWasTapped()

// good: the function clearly handles the notification
// A UIButton handler (EventSource=ConfirmButton, Action=Tapped)
handleConfirmButtonTapped()

Variables and Properties