Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 146 ยท Structures, Classes and Enums

Extensions in Depth

Master Swift extensions - add computed properties, methods, initializers, subscripts and nested types, adopt protocols, constrain with where clauses and know the limits.

An extension adds new behavior to a type that already exists. The type can be one you wrote, one from the standard library such as Int and Array, or one from a framework whose source you will never see. You do not need to subclass it or edit its file. This is one of the features that makes Swift code feel uniform: 5.isEven or names.second can look like they were always part of the language.

Extensions are also a tool for organizing your own code. Many Swift files declare a type with its stored properties and then use one extension per concern: one for protocol conformance, one for helpers, one for formatting. This lesson covers what extensions can add, what they cannot, how constraints work, and how to keep them tidy. The ideas build on properties, methods, initializers and protocols.

What an extension can add

flowchart LR
    T["Existing type<br/>(struct, class, enum, protocol)"] --> E["extension"]
    E --> A["computed properties"]
    E --> B["methods and static methods"]
    E --> C["convenience initializers"]
    E --> D["subscripts"]
    E --> F["nested types"]
    E --> G["protocol conformances"]

An extension can add all of these, but never stored properties.

Start with computed properties and methods on a standard-library type:

Swift Extending Int

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.

Four things to notice:

  1. A computed property has no storage. It is a function in disguise, so it works in an extension.
  2. On a value type, a method that changes self must be marked mutating, exactly as in the original type.
  3. Swift.min and Swift.max use the module name to avoid clashing with Int's own min and max members. Module-qualified calls are a good habit inside extensions of types that have members with common names.
  4. static members work too, and apply to the type rather than to a value.

Initializers in extensions

An extension on a struct can add initializers, and it has one big advantage over writing them inside the struct: the compiler still generates the automatic memberwise initializer. If you put a custom init inside the struct body, the memberwise one disappears.

Swift Memberwise init survives an extension

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.

For a class, an extension may add only convenience initializers. A designated initializer (and deinit) must live in the class declaration itself, because the class has to guarantee that all of its stored properties are set up in one place. See initializers for the rules.

Swift
class Account {
    var owner: String
    init(owner: String) { self.owner = owner }
}

extension Account {
    convenience init() { self.init(owner: "Guest") }   // fine
    // init(id: Int) { ... }                             // error: designated init not allowed here
}

Subscripts and nested types

Subscripts and nested types can be added in the same way. A nice pattern is a safe subscript that returns an optional instead of crashing:

Swift A safe subscript and a nested type

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 nested enum is spelled String.Casing from outside. Giving small helper types a home inside the type they belong to keeps the global namespace clean.

Adopting protocols with an extension

Writing conformance in its own extension is the most common use in real projects. It groups the required members, lets you read the type's main declaration without noise, and lets you add a conformance later without touching the original file.

Swift One extension per protocol

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.

Comparable gives sorted(), max(), >, <= and friends for free. Because Temperature has only one stored Double, the compiler can synthesize Equatable automatically when you declare it in the same file as the type. Declaring Equatable or Hashable in an extension in another file does not get that free synthesis. See Equatable and Hashable.

You can make a type you do not own conform to a protocol you do not own, for example extension Date: Identifiable. This is called a retroactive conformance. It works, but if the library later adds the same conformance, your program has two. Swift 6 asks you to write extension Date: @retroactive Identifiable to show that you know the risk.

Constraining an extension with where

You can restrict an extension to the cases where it makes sense. Add a where clause, and the members exist only for those types.

flowchart TD
    A["extension Array where Element: Numeric"] --> B["Array of Int: has total"]
    A --> C["Array of Double: has total"]
    A --> D["Array of String: no total"]

A constrained extension shows up only on the specializations that satisfy the constraint.

Swift Members that exist only when the elements allow them

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 constraint can name a protocol (Element: Numeric) or fix the type exactly (Wrapped == String). Extending Collection instead of Array makes isSorted available on arrays, slices, sets with ordered elements, and your own collections. This is the same mechanism the standard library uses to give you sorted() only when the elements are Comparable. For constraints on protocol extensions, and the static-versus-dynamic dispatch trap, read protocol extensions and conditional conformance.

Limits: what an extension cannot do

  • No stored properties. An extension cannot change the memory layout of the type. Use a computed property, or store the data somewhere else.
  • No overriding of existing methods. If a method already exists, an extension can add an overload with a different signature but cannot replace the original.
  • No designated initializers or deinit on classes.
  • No property observers (didSet) on properties declared elsewhere.

Name clashes deserve care. If you add func contains(_:) to a type from a library and the library adds the same name later, the compiler may pick either one, and the behavior of your program can change after a library update. Prefix unusual helpers or use a clearly project-specific name (containsIgnoringCase).

Access control and organization

An extension has its own default access level, and a modifier on the extension applies to every member inside it. Private members in an extension in the same file can still reach private members of the type.

Swift Organizing a type with extensions

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 private money helper is invisible outside its extension. The struct holds the data, and each extension holds one job. Comments such as // MARK: - help editors build an outline.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these can an extension NOT add to a type?

    Stored properties change the memory layout of the type, so they must be declared in the original type. Extensions may add only computed properties.
  2. 2. Why might you declare a custom initializer in an extension of a struct instead of inside it?

    Adding any init inside the struct body suppresses the memberwise initializer; adding one in an extension does not.
  3. 3. What does extension Array where Element: Numeric { var total: Element { ... } } mean?

    The where clause limits the extension. [1, 2, 3].total compiles; ["a"].total does not.
  4. 4. Which initializer kind can an extension add to a class?

    A class must set up its stored properties in a designated initializer inside its own declaration. An extension can add convenience initializers that delegate to it.
  5. 5. What is the risk of a retroactive conformance such as extension Date: Identifiable?

    That is why Swift 6 asks you to spell it @retroactive, to show you accept the risk.

Summary

  • Extensions add computed properties, methods, initializers, subscripts, nested types and protocol conformances to existing types.
  • They cannot add stored properties, override existing members, or add designated initializers and deinit to classes.
  • Put struct initializers in an extension to keep the memberwise initializer.
  • A where clause makes members available only when the type satisfies the constraint.
  • Group a type's code with one extension per concern or protocol; keep access control in mind.
  • Be careful with retroactive conformances and name collisions with library code.

Next: Protocols