Created
February 11, 2016 13:37
-
-
Save akimacho/e3e31479788fab843bda to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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