-
Notifications
You must be signed in to change notification settings - Fork 0
/
Code.swift
140 lines (107 loc) · 2.14 KB
/
Code.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
/* Classes */
class Game {
var score = 0
func printScore() {
print("Your score is \(score)")
}
}
var newGame = Game()
newGame.score += 10
newGame.printScore()
/* Inheritance */
class SpecialGame: Game {
var multiplier = 2
override func printScore() {
print("Your score is \(score * multiplier)")
}
}
var newSpecialGame = SpecialGame()
newSpecialGame.score += 10
newSpecialGame.printScore()
/* Initializers */
class Vehicle {
let isElectric: Bool
init(isElectric: Bool) {
self.isElectric = isElectric
}
}
class Car: Vehicle {
let isConvertible: Bool
init(isElectric: Bool, isConvertible: Bool) {
self.isConvertible = isConvertible
super.init(isElectric: isElectric)
}
}
/* Deinitializers */
class Player {
var id: Int
init(id: Int) {
self.id = id
print("User \(id): is alive!")
}
deinit {
print("User \(id): is dead!")
}
}
for i in 1...3 {
let player = Player(id: i)
print("User \(player.id): is playing")
}
/* Checkpoint 7 */
class Animal {
var legs: Int
init(legs: Int) {
self.legs = legs
}
func speak() {
print("Hello, I am an animal with \(legs) legs.")
}
}
class Dog: Animal {
var breed: String
init(breed: String) {
self.breed = breed
super.init(legs: 4)
}
override func speak() {
print("Hello, I am a \(breed). Woof woof!")
}
}
class Corgi: Dog {
init() {
super.init(breed: "Corgi")
}
}
class Poodle: Dog {
init() {
super.init(breed: "Poodle")
}
}
var corgi = Corgi()
var poodle = Poodle()
corgi.speak()
poodle.speak()
class Cat: Animal {
var isTame: Bool
init(isTame: Bool) {
self.isTame = isTame
super.init(legs: 4)
}
override func speak() {
print("\(isTame ? "Meow, I am a house cat, feed me." : "Meow, I will eat you, human!")")
}
}
class Persian: Cat {
init() {
super.init(isTame: true)
}
}
class Lion: Cat {
init() {
super.init(isTame: false)
}
}
var persian = Persian()
var lion = Lion()
persian.speak()
lion.speak()