Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swift Sequences & Collections

greg3z
December 10, 2015

Swift Sequences & Collections

How sequences & collections work in Swift

greg3z

December 10, 2015
Tweet

More Decks by greg3z

Other Decks in Programming

Transcript

  1. extension Array { subscript(safe i: Int) -> Element? { return

    i >= 0 && i < count ? self[i] : nil } }
  2. struct Section<T> { let title: String let elements: [T] subscript(index:

    Int) -> T? { return elements[safe: index] } }
  3. let cars = ["911", "Cayman", "Cayenne"] let section = Section(title:

    "Porsche", elements: cars) section[1] // Optional("Cayman")
  4. struct ArrayGenerator<T>: GeneratorType { let array: [T] var currentIndex =

    0 init(_ array: [T]) { self.array = array } mutating func next() -> T? { return array[safe: currentIndex++] } }
  5. struct Section<T>: SequenceType { let title: String let elements: [T]

    func generate() -> ArrayGenerator<T> { return ArrayGenerator(elements) } }
  6. struct Section<T>: Indexable { let title: String var elements: [T]

    var startIndex: Int { return 0 } var endIndex: Int { return elements.count } subscript(index: Int) -> T? { … } func generate() -> ArrayGenerator<T> { … } }
  7. protocol Indexable { var startIndex: Index { get } var

    endIndex: Index { get } subscript(position: Index) -> Element { get } }
  8. struct Section<T>: CollectionType { let title: String var elements: [T]

    var startIndex: Int { return 0 } var endIndex: Int { return elements.count } subscript(index: Int) -> T? { … } func generate() -> ArrayGenerator<T> { … } }
  9. struct Section<T>: CollectionType { let title: String var elements: [T]

    var startIndex: Int { return 0 } var endIndex: Int { return elements.count } subscript(index: Int) -> T { return elements[index] } func generate() -> ArrayGenerator<T> { … } }
  10. struct Section<T>: CollectionType { let title: String let elements: [T]

    var startIndex: Int { return 0 } var endIndex: Int { return elements.count } subscript(index: Int) -> T { return elements[index] } subscript(safe index: Int) -> T? { return elements[safe: index] } func generate() -> ArrayGenerator<T> { … } }
  11. let cars = ["911", "Cayman", "Cayenne"] let section = Section(title:

    "Porsche", elements: cars) section.count // 3 section.first // Optional("911") section.isEmpty // false section.indexOf("Cayman") // 1
  12. struct Dictionary<K : Hashable, V> { subscript(key: K) -> V?

    subscript(position: DictionaryIndex<K, V>) -> (K, V) }
  13. let dic = ["a": "audi", "b": "bmw", "c": "citroen"] let

    index = dic.startIndex // DictionaryIndex<String, String> dic[index] // ("a", "audi") dic[index.advancedBy(1)] // ("b", "bmw") dic[index.advancedBy(3)] // Fatal error