April 2026
Intermediate
683 pages
25h 29m
English
On a more advanced note, we’ll conclude this chapter with a bunch of demonstrations of using generics in extensions. Naturally, generics can be made part of extensions too; there isn’t much specific to it. Still, it should prove useful to go over some concrete syntax examples.
Let’s start with a simple example. Listing 11.24 contains a demonstration in which the generic Box struct is extended with the describe function. As expected, the client code can access box.describe() as if it was originally part of the Box struct.
struct Box<T> { let value: T}extension Box { func describe() -> String { return "Box holds: \(value)" }}let box = Box(value: "papers")print(box.describe()) // Box holds: papers
Listing 11.24 ...
Read now
Unlock full access