This article has been archived, as it was published several years ago, so some of its information might now be outdated. For more recent articles, please visit the main article feed.
Swift’s composition operator
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()
}
}

Swift by Sundell is brought to you by the Genius Scan SDK — Add a powerful document scanner to any mobile app, and turn scans into high-quality PDFs with one line of code. Try it today.