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

Functional networking

Published on 17 May 2019
Basics article available: Networking

Instead of complex network managers, or view controllers containing hundreds of lines of networking code, I always try to reduce my networking into functions that I can pass into my view controllers:

// With Futures/Promises:
typealias Loading<T> = () -> Future<T>

// Without Futures/Promises:
typealias Loading<T> = (@escaping (T) -> Void) -> Void

// If we model our networking code using functions, our view
// controllers no longer need to be aware of any networking,
// and can simply call those functions in order to retrieve
// their data:
class ProductViewController: UIViewController {
    private let loading: Loading<Product>

    init(loading: @escaping Loading<Product>) {
        self.loading = loading
        super.init(nibName: nil, bundle: nil)
    }

    func loadProduct() {
        loading().observe {
            ...
        }
    }
}

Support Swift by Sundell by checking out this sponsor:

Essential Developer

Essential Developer: Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for developers who want to become complete senior iOS developers. This virtual event includes lectures, mentoring sessions, and step-by-step instructions. Click to learn more.