Articles, podcasts and news about Swift development, by John Sundell.

Specializing generics with type aliases

Published on 17 Jul 2019
Basics article available: Generics

There are so many cool ways that Swift’s type aliases can be used. Here’s an example of specializing a generic using a type alias — which can then be extended and even subclassed!

// Type aliases can be used to easily specialize generics,
// without needing to actually create any additional "real" types.
typealias ProductLoader = ModelLoader<Product>

// Equivalent to 'extension ModelLoader where Model == Product'
extension ProductLoader {
    convenience init(networking: Networking) {
        self.init(networking: networking,
                  endpoint: Endpoint.product)
    }
}

// Equivalent to 'class DiscountedProductLoader: ModelLoader<Product>'
class DiscountedProductLoader: ProductLoader {
    ...
}

Support Swift by Sundell by checking out this sponsor:

Emerge

Emerge: Continuously monitor and reduce your app’s size. Emerge’s easy to use plugins for GitHub and fastlane will automatically scan your app’s binary and provide you with simple, actionable suggestions on how to make it smaller and, in turn, faster for your users to download. Set up a demo now!