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