#66: where Clauses in Swift Generics

A where clause lets you describe extra generic constraints in a readable way.

func commonElements<S1: Sequence, S2: Sequence>(_ a: S1, _ b: S2) -> [S1.Element]
where S1.Element == S2.Element, S1.Element: Hashable {
    let setB = Set(b)
    return a.filter { setB.contains($0) }
}

Without where, signatures like this become much harder to parse.

It is one of the best tools for keeping generic code powerful without making it unreadable.


I'm also on Twitter and GitHub.

Subscribe via RSS.