Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 146 ยท Structures, Classes and Enums

Nested Types and Extensions

Learn Swift nested types and extensions - define types inside types, add computed properties, methods, initializers and protocol conformance to existing types, and organize code with extensions.

Two Swift features help you shape code around the types you already have. Nested types let you declare a type inside another type, so a helper that only makes sense in one place lives in that place. Extensions let you add new behavior to a type that already exists, even one you did not write, such as Int, String or Array. Both are about organization: keeping related things together and keeping the global namespace clean.

Neither feature adds anything you could not do some other way, but together they change how Swift code reads. The standard library itself is full of them: Optional is extended with methods, Dictionary has a nested Keys type, and Array gets whole families of behavior from extensions on its protocols. This lesson explains how to declare nested types, how to use extensions for properties, methods, initializers, subscripts and protocol conformance, what extensions cannot do, and how to structure files with them. You should know structs, enums, properties and protocols basics.

Nested types

Declare a type inside the braces of another type. The inner type belongs to the outer type's namespace, so its full name is Outer.Inner:

Swift An enum nested in a struct

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.

Suit and Rank only make sense as parts of a Card, so they live inside it. Inside Card you can write Suit and Rank directly, which is why let rank: Rank works. Outside, you must say Card.Suit, which makes the origin obvious and prevents a clash with some other Suit in a different part of the program. A type can nest as deeply as you like, though more than two levels is usually a sign you should split things up.

Nested types can be structs, classes or enums (and you can nest generic types too). They follow the usual access control: an inner type can be private to hide it from the rest of the program.

Swift A private helper 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.

Line is an implementation detail. Code outside Receipt cannot create or even mention one, so you can change its shape later without breaking anyone. Try it: writing Receipt.Line(...) from outside produces an error that the type is inaccessible due to private protection level.

Generic types and nested types

A nested type can use the generic parameters of its outer type. The standard library's Dictionary<Key, Value>.Keys is the model. Here is a small stack with a nested iterator-like helper:

Swift A nested type inside a generic 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.

Snapshot is available as Stack<String>.Snapshot and uses the same Element. Because of this, nested types in generic types are generic too, even though you never write the angle brackets on them.

Extensions: adding to existing types

An extension adds new functionality to an existing type. You write extension TypeName { ... } and put the new members inside. Extensions work on structs, classes, enums and protocols, including types from the standard library and from frameworks whose source you cannot change.

Computed properties and methods

Swift Extending Int and String

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.

These extensions look as if Int always had isEven. Inside an extension, self is the instance, and a method that changes the instance must be marked mutating (for value types), exactly as in the type's own declaration. For classes there is no mutating, since methods can change properties anyway.

Initializers

Extensions can add convenience initializers. There is a valuable rule here: if you add an initializer to a struct in an extension (in the same module), the struct keeps its automatic memberwise initializer. If you add it inside the struct body, the memberwise one disappears.

Swift Initializers in an extension keep the memberwise init

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 extension adds init(gray:) and two static constants, while Color(red:green:blue:) is still free. For classes, an extension may only add convenience initializers, since the designated ones have to live in the class itself (Initializers).

Subscripts and nested types

Extensions can also add subscripts and nested types. Here a nested enum is added to Int to describe its sign:

Swift Nested types and subscripts from 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.

Digits are counted from the right: 746381295[0] is 5 and [8] is 7. The nested Sign type is reachable as Int.Sign.

Protocol conformance via extensions

Extensions are the standard way to make a type conform to a protocol, especially when the protocol is not the main purpose of the type, or when you do not own the type:

Swift Conforming in 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.

Several things happen here. Int conforms to a protocol it never heard of, which is called retroactive conformance and is perfectly legal. The Array extension is conditional: arrays are Summarizable only when their elements are, which is why both [1, 2, 3] and an array of temperatures work. And Temperature gains Comparable by writing only <; the other comparison operators come for free, and sorted() works. See Conditional Conformance for more.

Retroactive conformance of a type you do not own to a protocol you do not own (for example making Array conform to a protocol from someone else's library) is risky. If that library later adds the same conformance, your program can break. In Swift 6 the compiler warns about this and wants an explicit @retroactive marker. Add conformances for either your own type or your own protocol whenever you can.

What extensions cannot do

Extensions add behavior, not storage. You cannot add stored properties, because that would change the memory layout of a type that other code has already been compiled against.

Swift Stored properties in an extension (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 property with error: extensions must not contain stored properties. A computed property is fine (var label: String { "point" }), and so is a static stored property (static var count = 0, subject to the concurrency rules of Swift 6). If you need per-instance storage, change the original type or wrap it in your own type.

Other limits worth remembering:

  • An extension cannot add designated initializers or deinit to a class.
  • It can add new methods to a class but, in general, cannot override existing ones.
  • Extension members are visible everywhere the extension is visible, so public extensions on standard types affect your whole module, and name clashes between two modules' extensions can be ambiguous.

Organizing a type with extensions

A common style groups a type's members into several extensions, one for each purpose. The core stored properties and the main initializer stay in the type body, and each protocol gets its own extension:

Swift One extension per concern

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 file now reads like a table of contents. If every member is in the main body, a long type gets hard to scan. If you split too much, code gets scattered, so use extensions to reflect real groupings and not just to make the file longer.

There is one more practical detail: extensions in the same file can see private members of the type they extend. Since Swift 4, private is visible inside the declaration and any extensions of it in the same file. That lets you split a type into extensions without making everything fileprivate.

Swift private members are visible to extensions in the same file

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.

Putting both together

Nested types and extensions combine well: an extension can add a nested type, and a nested type can have its own extensions. A practical pattern is to namespace related types: enum API { struct User {} ; struct Order {} } uses a caseless enum as a pure namespace, which cannot be instantiated by accident. Use that technique modestly; Swift modules are already namespaces, and deeply nested names get tiring to read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you refer to a nested enum Suit declared inside struct Card from outside Card?

    A nested type belongs to the namespace of its outer type, so outside code writes Card.Suit.
  2. 2. Which of these can an extension NOT add to a struct?

    Extensions add behavior but not storage. Stored instance properties would change the memory layout of the type.
  3. 3. Why prefer adding init(gray:) to a struct in an extension instead of in the struct body?

    Defining a custom initializer in the main body removes the memberwise initializer. Putting it in an extension preserves it.
  4. 4. What does extension Array: Summarizable where Element: Summarizable mean?

    This is a conditional conformance. The array conforms only for element types that themselves conform.
  5. 5. Inside an extension, how do you refer to the current instance and mark a method that modifies a struct?

    An extension method uses self like any method. If the type is a value type and the method changes it, mark it mutating.

Summary

  • A nested type is declared inside another type and named Outer.Inner from outside; use it for helpers that belong to one type, and private to hide details.
  • Nested types in generic types can use the outer type's generic parameters.
  • An extension adds computed properties, methods, initializers, subscripts, nested types and protocol conformance to an existing type, even one from the standard library.
  • Extensions cannot add stored instance properties, or designated initializers and deinit for classes.
  • Put struct initializers in extensions to keep the memberwise initializer.
  • Conform to protocols in extensions, use where for conditional conformance, and be careful with retroactive conformance of types and protocols you do not own.
  • Extensions in the same file can use the type's private members, which makes splitting a type into thematic extensions easy.

Next: Value vs. Reference Semantics