concept compile time in category swift

appears as: compile time
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

Swift can’t stop you from writing bugs or poor code, but it does help reduce program errors at compile time using various techniques, including, but not limited to, static typing and strong support for algebraic data types (enums, structs, and tuples). Swift also prevents null errors thanks to optionals.

Figure 7.1. Generic code is turned to specialized code at compile time.

Protocols bring a lot of power and flexibility to your code. Some might say it’s Swift’s flagship feature, especially since Apple markets Swift as a protocol-oriented-programming language. But as lovely as protocols are, they can become difficult fast. Plenty of subtleties are involved, such as using protocols at runtime or compile time, and constraining protocols with associated types.

  • How would you decide to use a generic or nongeneric protocol in the struct? The delegate is a single type; you can safely use a generic here. You get compile-time benefits, such as extra performance, and seeing at compile time which type you’ll use. The code could look like this:
    protocol APIDelegate {
        func load(completion:(Data) -> Void)
    }
    
    struct ApiLoadHandler: APIDelegate {
        func load(completion: (Data) -> Void) {
            print("I am loading")
        }
    }
    
    class API<Delegate: APIDelegate> {
        private let delegate: Delegate?
    
        init(delegate: Delegate) {
            self.delegate = delegate
        }
    }
    
    let dataModel = API(delegate: ApiLoadHandler())
  • 8.1. Runtime versus compile time

    So far, this book has covered generics extensively and how they relate to protocols. With generics, you create polymorphic functions defined at compile time. But protocols don’t always have to be used with generics if you want to gain particular runtime—also known as dynamic dispatch—benefits. In this section, you’re going to create a protocol, and then you’ll see how to make trade-offs between generics constrained by protocols, and how to use protocols as types without using generics.