December 2015
Intermediate to advanced
400 pages
13h 3m
English
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 ...
Read now
Unlock full access