-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathContents.swift
287 lines (214 loc) · 10.3 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//: [Previous](@previous)
/*:
Stack is a common data structure in Comouter Science. Conceptually the data strcuture works using Last In First Out (LIFO) principle. Actually you already know how this principle works even if these are the first steps in programming. LIFO principle can be easily expressed as a stack of books: the last book added to the stack is the first one removed. Of cource, in real life you can remove any book that you want, we have more freedom to act, but imagine that books are stored in a container. That contaier physically restricts you from removing the last book, so you are forced to remove the top one in order to get to the last one. As I said - you already know what LIFO and Stack is.
That introduction was mostly conceptual. Now lets dive into technical details and think about how we can implement such behaviour. First of all lets decide if Stack should be implemented as a class or a struct. Since structures in Swift are far more powerful than in other C-based programming languages and you can use the same protocol-oriented approach as you can with classes, it is a good idea to use structures over classes. Structures will allow us to create simple building blocks that are restricted from the box - meaning that you do not need to worry about inheritence, deinitialization and reference management.
Lets think about the minimum required interface for our Stack data structure:
Methods:
- push() - adds a new element to the top of the stack
- pop() - removes and returns an element from the top of the stack
- peek() - returns an elemtn form the top, but does not remove it
Properties:
- isEmpty - returns a boolean indicator that tells if stack is empty or not
- count - contains the current number of elemtns in stack
Stack can be implemented by using Array or Linked List data structures; each one has its pros and cons depending on the perfomance characteristics required.
*/
import UIKit
public struct Stack<T> {
// MARK: - Private properties
private var elements: [T]
// MARK: - Public computed properties
public var isEmpty: Bool {
return elements.isEmpty
}
public var count: Int {
return elements.count
}
// MARK: - Initializers
public init() {
elements = [T]()
}
public init<S: Sequence>(stack: S) where S.Iterator.Element == T {
self.elements = Array(stack.reversed())
}
// MARK: Methods
public mutating func push(element: T) {
elements.append(element)
}
public mutating func peek() -> T? {
return elements.last
}
public mutating func pop() -> T? {
return elements.popLast()
}
}
/*:
Basically we created wrapper around standard Array type. However we need to carefully take a look at the two important pieces of the implenentation:
- T type which is a generic placeholder
- Custom initializer that accepts iterator element of Sequence protocol - this is simply a complementary initializer that allows client-developer to pass other Stack structs, Arra or any other type that conforms to Sequnce protocol to use it at initialization phase. Convenience and compatability with standard library - nothing sophisticated.
The following extension adds support for debugging capabilites for both regular "print" and "debugPrint" statements
*/
extension Stack: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return elements.description
}
public var debugDescription: String {
return elements.description
}
}
/*:
Adds support for new behaviour when Stack can be initialized by an array literal e.g. [1,2,3,4] for appropriate cases. Again, this is for convenince and compatability with the standard library and other data structures.
*/
extension Stack: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: T...) {
self.init()
elements.forEach { element in
self.elements.append(element)
}
}
}
/*:
Adds support for Sequence protocol. The Swift's runtime will call the makeIterator() method to initialize the for...in loop. All we need to do is to return some soft of iterator instance that conforms to IteratorProtocol. Iterator protocol allows us to return an iterator based on the type of elements out target type contains - in this particular case it is Stack.
*/
extension Stack: Sequence {
public func makeIterator() -> AnyIterator<T> {
let idexedIterator = IndexingIterator(_elements: self.elements.lazy.reversed())
return AnyIterator(idexedIterator)
}
}
/*:
Now lets create a sample Stack from an array literal and play around with the implementation:
*/
var stack: Stack = [1,2,3,4,5,6,7,8,1]
stack.forEach { element in
debugPrint("element: ", element)
}
// Explicitly cast to Any to silence compiler warning.
let lastElement = stack.pop() as Any
debugPrint("last removed element: ", lastElement)
stack.push(element: 10)
debugPrint("pushed 10: ", stack)
/*:
Great! Everything works as expected. Now time to move on and implement visualization using SpriteKit framework. Thankfully our Stack is generic which means that we can easily create some custom SKSpriteNode classes and visualize the data structure.
*/
import SpriteKit
import PlaygroundSupport
class StackScene: SKScene {
var stackElements: Stack<StackElementNode>! {
didSet {
if stackElements != nil {
numberOfElements.text = "\(stackElements.count) books"
}
}
}
lazy var numberOfElements: SKLabelNode = {
let label = SKLabelNode(text: "0 books")
label.position = CGPoint(x: 500, y: 300)
label.color = .gray
label.fontSize = 28
label.verticalAlignmentMode = .center
return label
}()
override func didMove(to view: SKView) {
stackElements = createRandomStackElementNodeArray(for: 4)
appearenceAnimation()
popButton()
pushButton()
label()
description()
addChild(numberOfElements)
}
func label() {
let nameLabel = SKLabelNode(text: "Stack")
nameLabel.position = CGPoint(x: 300, y: 760)
nameLabel.color = .gray
nameLabel.fontSize = 64
nameLabel.verticalAlignmentMode = .center
addChild(nameLabel)
}
func description() {
let nameLabel = SKLabelNode(text: "Limit is 9 books")
nameLabel.position = CGPoint(x: 300, y: 700)
nameLabel.color = .darkGray
nameLabel.fontSize = 24
nameLabel.verticalAlignmentMode = .center
addChild(nameLabel)
}
func popButton() {
let popButton = SKSpriteNode(color: .white, size: CGSize(width: 120, height: 50))
popButton.position = CGPoint(x: 100, y: 700)
popButton.name = "pop"
let popLabel = SKLabelNode(text: "Pop")
popLabel.fontColor = SKColor.darkGray
popLabel.fontSize = 24
popLabel.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center
popButton.addChild(popLabel)
addChild(popButton)
}
func pushButton() {
let pushButton = SKSpriteNode(color: .white, size: CGSize(width: 120, height: 50))
pushButton.position = CGPoint(x: 500, y: 700)
pushButton.name = "push"
let pushLabel = SKLabelNode(text: "Push")
pushLabel.fontColor = SKColor.darkGray
pushLabel.fontSize = 24
pushLabel.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center
pushButton.addChild(pushLabel)
addChild(pushButton)
}
func appearenceAnimation() {
// Animate creation of the stack of books
let appearAction = SKAction.unhide()
for (index, book) in stackElements.reversed().enumerated() {
book.position = CGPoint.init(x: 300, y: 500)
book.isHidden = true
addChild(book)
let moveDown = SKAction.move(to: CGPoint(x: 300, y: CGFloat(50 * CGFloat(index + 1))), duration: 1.5)
let waitAction = SKAction.wait(forDuration: TimeInterval(index * 2))
let sequence = SKAction.sequence([waitAction, appearAction, moveDown])
book.run(sequence)
}
}
func createRandomStackElementNodeArray(for numberOfElements: Int) -> Stack<StackElementNode> {
var nodes: Stack<StackElementNode> = Stack()
for _ in 0..<numberOfElements {
let node = StackElementNode()
nodes.push(element: node)
}
return nodes
}
// MARK: - Overrides
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let selfLocation = touches.first?.location(in: self) else {
return
}
let nodes = self.nodes(at: selfLocation)
for node in nodes {
if node.name == "pop" {
// pop action
let element = stackElements.pop()
let moveUpAction = SKAction.move(by: CGVector(dx: 0, dy: 200), duration: 2.0)
let fadeOut = SKAction.fadeOut(withDuration: 1.0)
let removeAction = SKAction.removeFromParent()
let actionSequence = SKAction.sequence([moveUpAction, fadeOut, removeAction])
element?.run(actionSequence)
} else if node.name == "push", stackElements.count <= 8 {
let node = StackElementNode()
node.position = CGPoint.init(x: 300, y: 600)
node.isHidden = true
addChild(node)
stackElements.push(element: node)
let appearAction = SKAction.unhide()
let moveDown = SKAction.move(to: CGPoint(x: 300, y: CGFloat(50 * CGFloat(stackElements.count))), duration: 1.5)
let waitAction = SKAction.wait(forDuration: TimeInterval(1))
let sequence = SKAction.sequence([waitAction, appearAction, moveDown])
node.run(sequence)
}
}
}
}
let skScene = StackScene(size: CGSize(width: 600, height: 800))
skScene.backgroundColor = .black
let skView = SKView(frame: CGRect(x: 0, y: 0, width: 600, height: 800))
skView.presentScene(skScene)
PlaygroundPage.current.liveView = skView
//: [Next](@next)