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()