-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathContents.swift
61 lines (43 loc) · 1.16 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import Foundation
struct Book {
var author: String
var name: String
}
struct Books {
var category: String
var books: [Book]
}
struct BooksIterator: IteratorProtocol {
// MARK: - Properties
private let books: [Book]
private var current = 0
// MARK: - Initializers
init(books: [Book]) {
self.books = books
}
// MARK: - Methods
mutating func next() -> Book? {
defer { current += 1 }
return books.count > current ? books[current] : nil
}
}
extension Books: Sequence {
func makeIterator() -> AnyIterator<Book> {
var iterator = books.makeIterator()
return AnyIterator {
while let next = iterator.next() {
return next
}
return nil
}
}
// func makeIterator() -> BooksIterator {
// return BooksIterator(books: books)
// }
}
let gameOfOwls = Book(author: "King", name: "Game of Owls")
let candyFactory = Book(author: "Martin", name: "Candy Factory and Crazy Cat")
let books = Books(category: "Favorite Books", books: [gameOfOwls, candyFactory])
books.forEach { book in
print(book)
}