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

Swift’s composition operator

Published on 29 Mar 2019

Swift’s & operator is really powerful. Not only does it let us compose multiple protocols, we can also use it to combine concrete types and protocols as well:

protocol Reloadable {
    func reload()
}

// Using the '&' operator, we can not only compose multiple
// protocols — we can also combine a concrete type with a
// protocol to form a brand new type.
typealias ReloadableViewController = UIViewController & Reloadable

// Our above type alias acts like a proper type in most cases,
// we can even inherit directly from it!
class ProfileViewController: ReloadableViewController {
    private lazy var tableView = UITableView()

    func reload() {
        tableView.reloadData()
    }
}

Support Swift by Sundell by checking out this sponsor:

Genius Scan SDK

Genius Scan SDK: Add a powerful document scanner to any iOS app. Genius Scan’s SDK features advanced image processing that’s the result of over 10 years of research and development and can be fully customized and integrated into your app with just one line of code. Mention Swift by Sundell when requesting a free demo to get a 20% discount on your license for a whole year.