This is an update to the topic covered earlier. You can read about the Protocols in detail in the original article. Collection Type, Sequence Type & Indexable Type
Most of the things are the same here are some of the changes:
- The Indexable protocol is now not necessarily required. All the aspects of the indexable protocol now fall under the Collection Protocol
- The names of the protocols have changed from SequenceType & CollectionType to Sequence & Collection
- The keyword Generator has been renamed to Iterator. Accordingly the generate function has been renamed makeIterator function.
- The collection protocol now requires the implementation of the function index, this function returns the value of the next index.
The sample code below should clarify
class CustomStack
{
var data : [Element] = [Element]()
func push(Element newElement : Element)
{
data.append(newElement)
}
func pop() -> Element
{
return data.removeLast()
}
}
//Additional Implementations - not strictly required
extension CustomStack
{
typealias Index = Int
var startIndex : Index
{
return 0
}
var endIndex: Index
{
return (data.count - 1)
}
subscript (position : Index) -> Element
{
return data[position]
}
}
extension CustomStack : Sequence
{
typealias Iterator = AnyIterator
func makeIterator() -> Iterator
{
var index = 0
return AnyIterator({() -> Element? in
if index < self.data.count
{
let res = self.data[index]
index += 1
return res
}
return nil
})
}
}
extension CustomStack : Collection
{
typealias SubSequence = CustomStack
subscript (bounds: Range) -> CustomStack.SubSequence
{
let newStack : CustomStack = CustomStack()
for i in bounds.lowerBound...bounds.upperBound
{
newStack.push(Element: data[i])
}
return newStack
}
/// Returns the position immediately after the given index.
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
func index(after i: Int) -> Int
{
if i < endIndex
{
return i + 1
}
return i
}
}