Skip to content

Instantly share code, notes, and snippets.

@akimacho
Created February 11, 2016 13:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akimacho/e3e31479788fab843bda to your computer and use it in GitHub Desktop.
Save akimacho/e3e31479788fab843bda to your computer and use it in GitHub Desktop.
import Foundation
protocol Iterator {
func hasNext() -> Bool
func next() -> AnyObject
}
protocol Aggregate {
func iterator() -> Iterator
}
class Book {
var name: String?
init(name: String) {
self.name = name
}
}
class BookShelf: Aggregate {
private var books: [Book] = []
var length: Int {
get {
return books.count
}
}
func getBookAt(index: Int) -> Book {
return books[index]
}
func appendBook(book: Book) {
self.books.append(book)
}
func iterator() -> Iterator {
return BookShelfIterator(bookShelf: self)
}
}
class BookShelfIterator: Iterator {
private var bookShelf: BookShelf
private var index = 0
init(bookShelf: BookShelf) {
self.bookShelf = bookShelf
}
func hasNext() -> Bool {
if self.index < bookShelf.length {
return true
} else {
return false
}
}
func next() -> AnyObject {
return bookShelf.getBookAt(self.index++)
}
}
print("Program start ...")
let bookShelf = BookShelf()
bookShelf.appendBook(Book(name: "Around the World in 80 Days"))
bookShelf.appendBook(Book(name: "Bible"))
bookShelf.appendBook(Book(name: "Cinderella"))
bookShelf.appendBook(Book(name: "Around the World in 80 Days"))
bookShelf.appendBook(Book(name: "Daddy-Long-Legs"))
let itr = bookShelf.iterator()
while itr.hasNext() {
let book = itr.next() as! Book
if let n = book.name {
print(n)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment