Паттерн Iterator
10 января 2017, 11:38
Пример
//: Playground - noun: Паттерн Iterator import UIKit struct BanksLevel{ let price:Double let time:UInt32 let comment:String } struct Levels { let arLevels: [BanksLevel] } struct LevelsIterator: IteratorProtocol { private var current = 0 private let levels: [BanksLevel] init(levels: [BanksLevel]) { self.levels = levels } mutating func next() -> BanksLevel? { defer { current += 1 } return levels.count > current ? levels[current] : nil } } extension Levels: Sequence { func makeIterator() -> LevelsIterator { return LevelsIterator(levels: arLevels) } }
Применение
let arLevels = Levels(arLevels: [ BanksLevel(price: 1.06740, time: 1, comment: "Первый банковский уровень"), BanksLevel(price: 1.06210, time: 2, comment: "Второй банковский уровень") ] ) for level in arLevels { print("Определён: \(level)") }
Пример 2
import UIKit class Item{ let name:String init(_ name:String){ self.name = name } } class IteratableItems{ var arItems: [Item] = [] init(items:[Item]){ self.arItems = items } } class ItemIterator: IteratorProtocol{ private var current = 0 private let arItems: [Item] init(items:[Item]){ self.arItems = items } func next()-> Item?{ defer { current += 1 } return arItems.count > current ? arItems[current] : nil } } extension IteratableItems: Sequence { func makeIterator() -> ItemIterator { return ItemIterator(items: arItems) } }
Используем:
let arItems = IteratableItems(items: [Item("One"),Item("Two"),Item("Three")]) for item in arItems{ print("item: \(item.name)") }
Твитнуть
Поделиться
Поделиться
Запинить
Популярное