Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 146 ยท Advanced Swift

Designing Good APIs

Design Swift APIs that read clearly at the call site: naming rules, argument labels, mutating pairs, strong types, error design, deprecation and a review checklist.

Every type, function and property you make public is an API, even if the only user is a teammate (or you, six months from now). A good API makes the right thing easy, the wrong thing hard, and reads almost like a sentence at the place where it is used. A bad one forces the reader to jump to the declaration to learn what process(x, true, 3) means.

Swift has a well-known set of conventions, the API Design Guidelines, and the entire standard library follows them. That is why array.firstIndex(of: 3), string.hasPrefix("a") and dictionary.removeValue(forKey: "k") feel so consistent. In this lesson you will learn the principles behind those names in your own words, practice them on small examples, and extend them to error handling, types and evolving a public API without breaking users.

The most important sentence in the guidelines is this one: clarity at the point of use is your most important goal. Code is read far more often than it is written, and a declaration is written once but called many times. Judge a name by how the call reads, not the declaration.

Name for the call site

Read the call out loud. If it sounds like a clear English phrase, the API is probably good. Here are two versions of the same inventory type. Both work, but only one is pleasant to use:

Swift The same behavior, two APIs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both print the same numbers (7 and then 7 false), but compare the calls: old.upd("apple", 3, true) makes you guess what true means, while stock.remove(3, of: "apple") needs no explanation. The guidelines boil down to a handful of habits, and the rest of the lesson shows each of them in action:

  • Include all the words needed to avoid ambiguity. remove(at: position) beats remove(position), which might mean "remove this element".
  • Omit needless words. Types are already visible, so removeElement(element) repeats itself; remove(element) says enough.
  • Name by role, not by type. var greeting = "Hello" beats var string = "Hello"; func restock(from supplier: Supplier) beats func restock(from supplierObject: Supplier).
  • Avoid abbreviations unless they are universal (url, id, min). upd, rm and qty save four keystrokes and cost every reader a second.
  • Compensate for weak types. When a parameter is an Int or a String, a label such as of: or forKey: carries the meaning that the type cannot.

Argument labels

Swift lets a parameter have an argument label (used at the call site) and a parameter name (used inside the function). The two are separate on purpose, so you can write a good call and a good body (Argument Labels has the syntax). The rules of thumb:

  • Omit the label when the arguments are interchangeable or the first argument completes a phrase that is already clear: min(a, b), max(x, y), zip(a, b).
  • Make the first label part of a grammatical phrase with prepositions: x.removeFirst(3), view.move(to: point), list.index(of: item). If the first argument forms a phrase with the base name, drop its label (addSubview(view)), otherwise give it one (move(from:to:)).
  • Label every argument that is not a natural continuation of the phrase. Labels at the call site are mandatory in Swift, so the compiler enforces them for you:
Swift Labels are not optional (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler stops with error: missing argument labels 'from:to:' in call. Writing move(from: 1, to: 5) is correct and prints 4. Notice how each name plays a role: callers see from: and to:, and inside the body the same values are named start and end, which read better in an expression.

  • Give default values to parameters that are rarely changed. Defaults collapse a whole family of overloads into one and keep common calls short. This is progressive disclosure: the simple use is simple, and the power is available when needed.
Swift Defaults give progressive disclosure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You see ["Intro", "Alpha", "Beta"] and then ["Intro", "Alpha"] ["Intro", "Alpha", "Beta"]: removing(_:) returned a new playlist and left the original alone. The parameter is optional only because the common call should not have to mention it. Prefer defaults over overload sets, and put the defaulted parameters last.

Mutating and non-mutating pairs

Swift programmers expect a method to say whether it changes the receiver. The standard library has a consistent naming scheme that you should copy:

Mutating (verb) Non-mutating (returns a new value)
sort() sorted()
reverse() reversed()
formUnion(_:) union(_:)
append(_:) appending(_:) (for example URL.appending(path:))
removeAll(where:) filter(_:) (keeps the matches instead)

The rule: when the operation is naturally a verb, the mutating form uses the plain verb (sort) and the non-mutating form uses the participle (sorted, appending). When it is naturally a noun (union), the mutating form gets the prefix form (formUnion) and the non-mutating form keeps the noun.

Swift Following the standard library's naming pairs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

You get [1, 2, 3] [3, 1, 2] and then [1, 2, 3], followed by ["a", "b", "z"] and ["a", "b", "q"]. The custom Temperature follows the same pattern and prints 22.0 21.6, then 22.0. Because a reader who sees rounded() knows it returns a value, Swift can warn you if you forget to use the result of a non-mutating call, which would be a silent mistake with a mutating name.

More naming conventions

  • Booleans read as assertions about the receiver: isEmpty, isValid, hasPrefix(_:), contains(_:), intersects(_:).
  • Methods with side effects use verb phrases; methods without them use noun phrases: print(x), list.append(x) versus list.first, a.distance(to: b).
  • Factory methods start with make: makeIterator(), makeLayout().
  • Types and protocols: types are UpperCamelCase nouns (Playlist); protocols describing what something is are nouns (Collection), and capabilities end with able, ible or ing (Equatable, Sendable, CustomStringConvertible).
  • Everything else is lowerCamelCase, including enum cases (.red, not .Red).
  • Acronyms: uniformly upper-case or lower-case (urlString, userID, HTTPStatus), never mixed (Url).
  • Avoid "gotcha" repeats of the language: do not call a function getName(); a property name is enough, and a getter that does work can be a method named for what it does (makeName()).

Let types carry the meaning

Names help humans; types help the compiler, which never gets tired. A well designed API makes wrong code fail to compile.

First, do not use a String where a closed set of choices exists. A String accepts typos, an enum does not:

Swift Strings accept typos, enums and optionals do not (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

There are two errors: cannot convert value of type 'String' to expected argument type 'Color' and value of optional type 'Int?' must be unwrapped to a value of type 'Int'. The second one is the same idea. Int("5") returns an optional because parsing can fail, and the API forces every caller to decide what to do about that. Returning 0 or -1 for "not a number" would let the mistake slip through unnoticed.

Second, give different kinds of identifiers different types. A bare Int can be a user id, an order id or a count; a wrapper type makes mixing them impossible, at no run-time cost:

Swift Distinct identifier types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler rejects the call with error: cannot convert value of type 'UserID' to expected argument type 'OrderID'. With raw integers this bug would compile, run, and cancel somebody else's order. The pattern generalizes: use Duration instead of a Double of seconds, a URL instead of a String, and dedicated types for Money, Email, or Percentage when the domain has rules.

Third, make illegal states unrepresentable. If a download can be idle, running(progress) or finished(Data), model it as an enum with associated values, not as three optional properties that can contradict each other (see Enumerations).

Swift Failable initializers, preconditions and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The output is Optional(125), nil, nil and true. This type shows an important design decision: which kind of failure is it?

Designing for failure

Swift offers several ways to report a problem, and each fits a different situation:

Situation Tool Example
There may simply be no value Optional return Int("x"), dictionary[key]
An operation can fail and the caller needs to know why throws (or Result) reading a file, parsing input
A fixed, small set of known failures typed throws(MyError) parsers and validators
The caller broke the contract (a bug) precondition or fatalError negative money, index out of range

Use nil only when absence is the whole story. The moment a caller would ask "why?", throw an error that carries the reason. Make errors specific and actionable: an enum with cases and associated values, not a generic Error with a message string.

Swift An API that throws descriptive errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The loop prints ok: ada, error: The name has 2 characters, but needs at least 3., error: The name is empty. and error: The character ' ' is not allowed.. Because the initializer uses typed throws (throws(ValidationError)), the catch block receives a ValidationError, not a generic any Error, which lets callers switch over the cases. Typed throws suit small, closed error sets; for large modules a plain throws with a documented error type is more flexible, because adding a case later does not break callers (Typed Throws, Custom Errors).

A few more habits for failure design:

  • Do not make callers parse strings to learn what went wrong; give them cases and values.
  • Mark results that callers may reasonably ignore with @discardableResult (the standard library does this for removeLast() and Set.insert(_:)), and leave everything else alone so the compiler warns about dropped results:
Swift Unused results get a warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This prints done, plus the compiler warning result of call to 'pop()' is unused. There is no warning for push(1), because its author declared that ignoring the result is fine. Warning is the default, and the safe choice.

Keep the surface small

Everything public is a promise. Expose the smallest surface that does the job and hide the rest (Access Control):

  • Start with private and internal; widen only for a real use case. Adding public API later is easy, removing it is a breaking change.
  • Use private(set) for properties that callers may read but must not change, like songs in the playlist above.
  • Prefer protocols and generics to concrete types in parameters (some Sequence<Int> instead of [Int]) when you only need the capability. Prefer concrete types in results unless hiding them has a real benefit.
  • Prefer value types, so a caller cannot change your internals from the outside.
  • Keep initializers honest: if some combinations are invalid, either make them impossible with types or fail clearly.

Evolving an API without breaking users

Even careful APIs change. Swift has attributes that let you move users to the new design gradually, using the compiler as a messenger:

Swift Deprecating with a replacement hint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program still compiles and prints ["Old style", "New style"], but the compiler adds a warning: 'addBook' is deprecated: renamed to 'add(_:)' together with a note use 'add(_:)' instead. In Xcode that warning comes with a one-click fix. When the deprecation period ends, switch to @available(*, unavailable, renamed: "add(_:)"), which turns calls into errors with the same message and keeps the migration path visible. For platform-specific availability, @available(macOS 15, iOS 18, *) exists but only matters on Apple platforms.

Two more attributes matter for libraries distributed as binaries or packages (read-only here, because the runner builds a single file):

Swift
// read-only example: library-evolution attributes
@frozen public struct Point {   // layout will never change: the compiler can optimize across modules
    public var x: Double
    public var y: Double
}

@inlinable public func square(_ x: Double) -> Double {   // body becomes part of the ABI: change with care
    x * x
}

@frozen promises that stored properties will never change, @inlinable exposes the body to callers, and both limit what you can change later. Use them only when the performance is measured and the API is truly stable. Documentation is part of the contract too; the next lesson shows how to write it so that tools render it.

A review checklist

Before you publish an API, run through these questions:

  1. Does every call site read like a clear phrase when read aloud?
  2. Is any abbreviation, flag argument (true/false) or "magic number" hiding meaning? Replace flags with two methods or an enum.
  3. Would a wrong argument order or a mixed-up identifier compile? If yes, add types.
  4. Are mutating and non-mutating operations named as pairs?
  5. Do failures carry the information a caller needs, and are programmer errors separated from data errors?
  6. Is the public surface the smallest that works, with defaults for the rare options?
  7. Can you evolve it later (deprecation path, no accidental promises)?
  8. Is there a documentation comment with a one-line summary?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. According to the Swift API Design Guidelines, what is the most important goal?

    A declaration is written once but called many times, so the call site should read clearly. Brevity is a non-goal.
  2. 2. A type has sort() and sorted(). Which statement describes the convention?

    The verb form (sort) mutates in place, the participle (sorted) returns a new value and leaves the receiver alone.
  3. 3. What is the best way to prevent a user id from being passed where an order id is expected?

    Distinct types turn the mix-up into a compile-time error at no run-time cost.
  4. 4. Which fits a failable initializer (init?) or an optional return best?

    Use nil when absence is the whole story (Int("x")). If callers need the reason, throw an error with cases and values; for contract violations use precondition.
  5. 5. How does @available(*, deprecated, renamed: "add(_:)") help your users?

    Deprecation lets users migrate gradually: the code builds, the compiler suggests the new name, and you can later switch to unavailable.

Summary

  • Judge every name by how the call reads; include the words needed, omit the redundant ones, and avoid abbreviations.
  • Argument labels are mandatory at call sites; build grammatical phrases, give rare options default values and put them last.
  • Name mutating and non-mutating pairs as the standard library does: sort/sorted, formUnion/union.
  • Let types do the work: enums instead of strings, wrapper types for identifiers, optionals for absence, and enums with associated values to make illegal states impossible.
  • Choose the failure mechanism deliberately: nil when absence is the story, throws with descriptive cases when callers need a reason, precondition for bugs.
  • Keep the public surface small, prefer value types, and evolve with @available rather than breaking users.
  • Review with a checklist before publishing, and document the result.

Next: Documentation Comments