-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathclasses.swift
345 lines (270 loc) · 8 KB
/
classes.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import Foundation
class Example {
var a = 0
var b: String
init(a: Int) { // Constructor
self.a = a
b = "name" // An error if a declared property isn't initialized
}
}
// External param names are required...
let eg = Example(a: 1)
print(eg.a) // 1
// ...Unless the params are declared with leading underscores.
class Example2 {
var a = 0
var b = 0
init(_ a: Int, _ b: Int) {
self.a = a
self.b = b
}
}
let eg2 = Example2(1, 2)
print(eg2.a) // 1
print(eg2.b) // 2
// # Lazy properties
// Lazy properties' initial value aren't
// initialized until the first time the
// property is accessed.
class Podcast {
lazy var episode = Episode() // `var` declaration is required.
}
class Episode {
var audio = "somefile.mp3"
}
var podcast = Podcast() // episode has not been initialized yet.
print(podcast.episode.audio) // somefile.mp3
// # Computed properties
// Computed properties don't store a value. Instead, getters / setters
// are provided to retrieve and set _other_ properties.
class Window {
var x = 0.0, y = 0.0
var width = 100.0, height = 100.0
var center: (Double, Double) {
get {
return (width / 2, height / 2)
}
set(newVal) {
x = newVal.0 - (width / 2)
y = newVal.1 - (height / 2)
}
}
}
var win = Window()
print(win.center) // (50.0, 50.0)
win.center = (0.0, 10.0)
print(win.x) // -50.0
print(win.y) // -40.0
// The param to `set` can be omitted and a magic "newValue"
// can be used to referenced the new value.
/*
set {
x = newValue.0 - (width / 2)
}
*/
// # Read-only computed properties
class Song {
var title = ""
var duration = 0.0
var metaInfo: [String:String] {
return [
"title": self.title,
"duration": NSString(format: "%.2f", self.duration) as String,
]
}
}
var song = Song()
song.title = "Rootshine Revival"
song.duration = 2.01
print(song.metaInfo["title"]!) // Rootshine Revival
print(song.metaInfo["duration"]!) // 2.01
// # Property Observers
// Property observers can be added onto any properties
// (including inherited) except for lazy computed props.
class Website {
var visitors: Int = 0 { // An explicit type is required
willSet(newVisitorCount) { // Called before the prop is set
visitors = newVisitorCount + 1 // Warning. Can't set within its own willSet
}
didSet { // Called after a new val is set
print(visitors - oldValue) // oldValue is magically defined
}
}
}
var site = Website()
site.visitors = 1
print(site.visitors) // 1
// # Type Properties
// AKA class variables
class Body {
/* class var age = 0 // error: class variables not yet supported */
// Computed type property
class var size: Int {
return 10
}
}
print(Body.size) // 10
// # Type Methods
// AKA class methods
class Banana {
var color = "green"
class func genus() -> String {
return "Musa"
}
}
print(Banana.genus()) // Musa
// # Instance methods
class Month {
var name: String
init(name: String) {
self.name = name
}
func shortened() -> String {
return name[name.startIndex..<advance(name.startIndex, 3)]
}
}
print(Month(name: "January").shortened()) // Jan
// # Inheritance
// Swift classes do not inherit from a universal base class.
class Bicycle {
var tireWidth: Double
var topSpeed: Double
var name: String
var gears: Int
// Marking a method/property with `@final` prevents it from being overridden
final var color = "green"
init() {
tireWidth = 30.5
topSpeed = 10.0
name = "regular ol' bike"
gears = 3
}
func go(distance: Double) {
print("Went \(distance) at a top speed of \(topSpeed) in my \(name)")
}
}
class MountainBike : Bicycle {
/* var tireWidth = 64.0 // Cannot override property in the declaration */
override init() {
super.init()
tireWidth = 64.0
name = "mountain bike"
gears = 12
}
// Override parent's methods via `override` keyword
override func go(distance: Double) {
super.go(distance)
print("Did \(distance) on a mountain bike")
}
// A getter/setter override can _any_ inherited property.
override var topSpeed: Double {
get {
return super.topSpeed - 4.0
}
set {
super.topSpeed = newValue
}
}
// Property observer
override var gears: Int {
didSet {
print("Gears was changed to \(gears)")
}
}
}
var mountainBike = MountainBike() // Gears was changed to 12
mountainBike.topSpeed = 6.0
print(mountainBike.topSpeed) // 2.0
mountainBike.go(12.0) // Went 12.0 at a top speed of 10.0 in my mountain bike
// Did 12.0 on a mountain bike
// # Initializers
// 'Convenience' initializers overload empty
// initializers that populate the params
// in 'designated' initializers.
class iOS {
var version: String
init(version: String) {
self.version = version
}
convenience init() {
self.init(version: "8.0.0")
}
}
var os = iOS()
print(os.version) // 8.0.0
// # ARC and reference cycles
// Strong reference cycles happen when two objects
// hold strong references to each other so that neither
// can be deallocated (à la memory leaks in garbage collected langs)
// Strong references can be resolved by declaring
// references as `weak` or `unowned`
// Use a weak reference whenever it's valid for the reference
// to be nil at any point. These are optional types.
class Driver {
weak var car: Car? // Strong reference to car.
deinit {
print("Driver deinitialized")
}
}
class Car {
weak var driver: Driver? // Weak reference to driver.
deinit {
print("Car deinitialized")
}
}
var driver: Driver?
var car: Car?
driver = Driver()
car = Car()
driver!.car = car
car!.driver = driver
driver = nil // No more strong references to driver.
car = nil // No more strong references to car.
// Unowned references are like weak references except they always
// refer to a value, so they're non-nil.
class Artist {
var instrument: Instrument? // Strong reference to instrument.
}
class Instrument {
unowned let artist: Artist // Unowned reference to artist.
init (artist: Artist) {
self.artist = artist
}
}
var artist: Artist?
artist = Artist()
artist!.instrument = Instrument(artist: artist!)
artist = nil // Both objects are deallocated since there are no more strong references.
// # Access control
// Access control in Swift is very much package-based.
// `private`: Can only be accessed from the same source file that it's defined
// `internal`: Can be accessed anywhere in the target it's defined
// `public`: Accessible anywhere in the target and anywhere its module is imported
// Defaults to `internal` if not explicitly declared.
internal class Image { // Accessible in the same target
internal var name : String
private var mime : String { // Accessible only in this file. Never settable.
get {
return "image/\(name.pathExtension)"
}
}
init(name: String) {
self.name = name
}
}
var img = Image(name: "foo.png")
public class Webpage {
public var title : String
public var created : NSDate
private(set) var images : [Image] // Readable within the same target but only writable in this file
var slug : String {
return created.description + title
}
init(title: String) {
self.title = title
self.created = NSDate()
self.images = []
}
}
var webPage = Webpage(title: "blog post")
webPage.images.append(Image(name:"panda.gif"))