O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Type Constraint where Clauses

Write a new method that takes every element of an array and pushes it onto a stack.

Listing 22.17 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)")
}

pushAll(_:) is useful, but it is not as general as it could be. You now know that any type that conforms to Sequence can be used in a for-in loop, so why should this method require an array? It should be able to accept any kind of sequence – even another Stack, now that Stack conforms ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required