WWDC 2016, session 403: Swift API Design Guidelines

Posted on September 15, 2016


Omit needless words

Remove words that do not contribute to the meaning

// Use:
friends.remove(ted)

// Instead of:
friends.removeItem(ted)
friends.removeElement(ted)
friends.removePerson(ted)

Swift’s strong type system will make sure the compiler will give you a meaningful message if you try to do something like:

friends.remove(caffeine)
// Compiler says: cannot convert type ... to expected argument type ...

Take advantage of “real world” grammar

friends.remove(ted)
friends.remove(at: positionOfTed)

// If the first argument is part of a prepositional phrase, give it a label:
truck.removeBoxes(withLabel: "a label")

// If the first argument is not part of a grammatical phrase, give it a label:
viewController.dismiss(true)
// should be:
viewController.dismiss(animated: true)

// Otherwise, don't use a first argument label
friends.insert(michael, at: friends.startIndex)

Name methods based on their side effects

// Use a verb to describe the side effect
friends.reverse()
viewController.present(animated: true)

// Use a noun to describe the result
button.backgroundTitle(for: .disabled)

The “ed/ing” rule

x.reverse() // mutating
let y = x.reversed() // non-mutating

Objective-C compatibility (25:00)

Use the following methods for safe communication with Objective-C code

// No need to care about the Objective-C names when using the following:
#selector()
#selector(setter: Artist.name)
#selector(getter: Artist.name)
#keyPath(Album.arist.name)

// The name of anything that can be exposed to Objective-C from Swift
// can be controlled using the @objc keyword
extension MyController {
  @objc(handleDrag:forEvent:)
  func handleDrag(sender: UIControl, for event: UIEvent) {} // handleDrag(sender: for:)
}

Other resources

swift.org API Design Guidelines

Stay in touch!