November 2016
Intermediate to advanced
480 pages
14h 42m
English
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 ...
Read now
Unlock full access