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

Dependency injection using functions

Published on 23 Oct 2018

When I'm only using a single function from a dependency, I love to inject that function as a closure, instead of having to create a protocol and inject the whole object. Makes dependency injection and testing super simple.

final class ArticleLoader {
    typealias Networking = (Endpoint) -> Future<Data>
    
    private let networking: Networking
    
    init(networking: @escaping Networking = URLSession.shared.load) {
        self.networking = networking
    }
    
    func loadLatest() -> Future<[Article]> {
        return networking(.latestArticles).decode()
    }
}

Support Swift by Sundell by checking out this sponsor:

Bitrise

Bitrise: My favorite continuous integration service. Automatically build, test and distribute your app on every Pull Request, and use a new powerful suite of add-ons to visualize your test results, to ship your app with ease, and to add crash and performance monitoring to your project. Get started for free.