Weekly Swift articles, podcasts and tips by John Sundell.

Specializing protocols using constraints

Published on 09 Oct 2018
Basics article available: Protocols

A little late night prototyping session reveals that protocol constraints can not only be applied to extensions - they can also be added to protocol definitions!

This is awesome, since it lets us easily define specialized protocols based on more generic ones.

protocol Component {
    associatedtype Container
    func add(to container: Container)
}

// Protocols that inherit from other protocols can include
// constraints to further specialize them.
protocol ViewComponent: Component where Container == UIView {
    associatedtype View: UIView
    var view: View { get }
}

extension ViewComponent {
    func add(to container: UIView) {
        container.addSubview(view)
    }
}

Support Swift by Sundell by checking out this sponsor:

Magic Lasso Adblock
Magic Lasso Adblock

Magic Lasso Adblock: Block ads, trackers and pop-ups on your iPhone, iPad and Mac. Magic Lasso Adblock provides a 2.0x speed increase on common websites, improves your privacy by removing ad trackers and works with Safari across all devices. It’s as if Apple themselves had designed an ad blocker. Download for free today.