COLLECTION TYPE, SEQUENCE TYPE & INDEXABLE TYPE – Update

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:

  1. The Indexable protocol is now not necessarily required. All the aspects of the indexable protocol now fall under the Collection Protocol
  2. The names of the protocols have changed from SequenceType & CollectionType to Sequence & Collection
  3. The keyword Generator has been renamed to Iterator. Accordingly the generate function has been renamed makeIterator function.
  4. 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
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s