April 2026
Intermediate
683 pages
25h 29m
English
In Swift, a function can import or return a value that conforms to a protocol, such as a class or struct instance. Functions returning a protocol can effectively act like a factory or builder. Although this sounds simple enough, there are different ways to return protocol-conforming types, which will be explored in this section.
A function can use a protocol type directly. For instance, returning a strict protocol type via casting is the most basic approach. This approach is demonstrated in Listing 10.17, where you should focus on the makeRandomShape function.
protocol Shape { var area: Double { get }}class Circle: Shape { let radius: Double init(radius: Double) { self.radius
Read now
Unlock full access