Type Constraint where Clauses

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

Listing 22.17  Pushing items from an array onto a stack

...
func pushItemsOntoStack<Element>(inout stack: Stack<Element>,
                                            fromArray array: [Element]) {
    for item in array {
        stack.push(item)
    }
}

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

pushItemsOntoStack(_:fromArray:) takes its first argument, a Stack, as an inout argument so that it can call the mutating method push(_:). This function is useful, but it is not as general as it could be. You now know that any type that conforms to SequenceType can be used in a for ... in loop, so why should this ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.