Type Constraints in where Clauses

You have seen the powerful where keyword used to apply constraints to each iteration of a loop or a case of a switch statement. You can also use a where clause to further constrain generic arguments or return types in a function declaration.

Write a new method on Stack<Element> that takes every element of an array and pushes it onto a stack.

Listing 21.19  Pushing items from an array onto a stack

...
struct Stack<Element>: Sequence {
    ...
    mutating func pushAll(_ array: [Element]) {
        for item in array {
            self.push(item)
        }
    }
}
...
for value in myStack {
    print("for-in loop: got \(value)")
}

myStack.pushAll([1, 2, 3])
for value in myStack {
    print("after pushing: got \(value)")
}

Here, your pushAll(_:) ...

Get Swift Programming: The Big Nerd Ranch Guide, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.