Monday, February 2, 2015

Overview

In swift, when we want to iterate over a sequence, we use a generator. It’s not the same as a generator in python or in javascript. This post is all about how to create and use them. More information about them can be found here.

Content

In swift, like in all languages, we can iterate over a collection using a for each or better named for in in swift.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// array
for item in ["first", "second", "third"] {
    println(item)
}
// first
// second
// third


// dictionary
for (key, value) in ["key1":1, "key2":2, "key3":3] {
    println("key:\(key) value:\(value)")
}
// key:key1 value:1
// key:key2 value:2
// key:key3 value:3


// range
for i in 0..<3 {
    println(i)
}
// 0
// 1
// 2

This works for built in types but how can we use the for..in with our own classes? We have to add the SequenceType protocol to our class.

1
2
3
4
5
6
// Initial attempt
extension Cats : SequenceType {
    func generate() -> Generator {
        
    }
}

We have to return a Generator. A Generator has to conform to the GeneratorType protocol which has only one method, next().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct List<T> : GeneratorType {
  var currentNode : List<T>

  init(head: List<T>) {
    currentNode = head
  }

  mutating func next() -> T? {
    switch currentNode {
    case let cons as List<T>:
      currentNode = cons.next
      return cons.value
    default:
      return nil
    }
  }
}

Random Posts