-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathContents.swift
141 lines (101 loc) · 2.88 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import UIKit
protocol Product {
var name: String { get }
var calories: Int { get }
var price: NSNumber { get }
}
struct Apple: Product {
var name: String = "Apple"
var calories: Int = 50
var price: NSNumber = 3
init() { }
}
struct Banana: Product {
var name: String = "Banana"
var calories: Int = 85
var price: NSNumber = 5
init() { }
}
struct Juice: Product {
var name: String = "Orange Juice"
var calories: Int = 150
var price: NSNumber = 20
init() { }
}
struct NullObjectProduct: Product {
var name: String = "Void"
var calories: Int = 0
var price: NSNumber = 0
init() { }
}
extension Apple: CustomStringConvertible {
var description: String {
return "name: \(name), calories: \(calories), price: \(price)"
}
}
extension Banana: CustomStringConvertible {
var description: String {
return "name: \(name), calories: \(calories), price: \(price)"
}
}
extension Juice: CustomStringConvertible {
var description: String {
return "name: \(name), calories: \(calories), price: \(price)"
}
}
extension NullObjectProduct: CustomStringConvertible {
var description: String {
return "name: \(name), calories: \(calories), price: \(price)"
}
}
class Basket {
subscript(index: Int) -> Product {
get {
guard index > -1, index < products.count else {
return NullObjectProduct()
}
return products[index]
}
}
private var products: [Product] = []
func add(product: Product) {
products += [product]
}
}
extension Basket: CustomStringConvertible {
var description: String {
return "products: \(products)"
}
}
class MarketViewController: UIViewController {
// MARK: - Properties
var basket = Basket()
// MARK: - Initializers
init() {
/*
let banana = Product(name: "Banana", calories: 85, price: 5)
let apple = Product(name: "Apple", calories: 50, price: 3)
let juice = Product(name: "Orange Juice", calories: 150, price: 20)
basket.add(product: banana)
basket.add(product: apple)
basket.add(product: juice)
print(basket)
if let thirdProduct = basket[3] {
print("Third product: ", thirdProduct)
} else {
print("nil")
}
*/
basket.add(product: Banana())
basket.add(product: Apple())
basket.add(product: Juice())
print(basket)
let thirdProduct = basket[3]
print(thirdProduct)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let marketViewController = MarketViewController()