goat’s village(wonderful IT life)

IT でエンジニア人生謳歌しちゃう村

Iterator パターンを Swift で書き換えてみた

Java で書かれていたサンプルコードを、Swift で書き換えてみた。

/// アグリゲートの役
protocol Aggregate {
    func iterator() -> Iterator
}

/// イテレータの役
protocol Iterator {
    func hasNext() -> Bool
    func next() -> Any
}

/// 本を取り出す実体
final class Book {
    private let name: String
    init(name: String) {
        self.name = name
    }
    func getName() -> String {
        return self.name
    }
}

/// コンクリート・アグリゲートの役
final class BookShelf: Aggregate {
    private var books: [Book] = []
    private var last: Int = 0
    
    func getBookAt(index: Int) -> Book {
        return self.books[index]
    }
    
    func appendBook(book: Book) {
        self.books.append(book)
        self.last += 1
    }
    
    func getLength() -> Int {
        return self.last
    }
    
    func iterator() -> Iterator {
        return BookShelfIterator(bookShelf: self)
    }
}

/// コンクリート・イテレータの役
final class BookShelfIterator: Iterator {
    private var bookShelf: BookShelf
    private var index: Int
    
    init(bookShelf: BookShelf) {
        self.bookShelf = bookShelf
        self.index = 0
    }
    
    func hasNext() -> Bool {
        if self.index < self.bookShelf.getLength() {
            return true
        } else {
            return false
        }
    }
    
    func next() -> Any {
        let book = self.bookShelf.getBookAt(index: index)
        self.index += 1
        return book
    }
}

/// メイン
let bookShelf = BookShelf()
bookShelf.appendBook(book: Book(name: "テスト"))
bookShelf.appendBook(book: Book(name: "サンプル"))
bookShelf.appendBook(book: Book(name: "テストサンプル"))
bookShelf.appendBook(book: Book(name: "example"))
var it = bookShelf.iterator()
while it.hasNext() {
    let book = it.next() as! Book
    print((book.getName()))
}

参考文献 www.amazon.co.jp