Skip to content

Commit 28124fc

Browse files
committed
weak implementation.
1 parent 6a012ae commit 28124fc

File tree

1 file changed

+95
-0
lines changed
  • closureBeingCreative.playground/Pages/CaptureList.xcplaygroundpage

1 file changed

+95
-0
lines changed

closureBeingCreative.playground/Pages/CaptureList.xcplaygroundpage/Contents.swift

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,98 @@
22

33
import Foundation
44

5+
/*:
6+
Forming Strong Reference Cycles
7+
*/
8+
9+
// MARK: - Forming Strong Reference Cycles with two class
10+
class Jedi{
11+
let name: String
12+
var weapon: Lightsaber?
13+
14+
init(name: String) {
15+
self.name = name
16+
"\(name) is a Jedi now"
17+
}
18+
19+
deinit {
20+
"\(name) became one with the Force"
21+
}
22+
}
23+
24+
class Lightsaber{
25+
var owner: Jedi?
26+
let type: String
27+
let model: String
28+
29+
init(type: String, model: String) {
30+
self.type = type
31+
self.model = model
32+
"The \(type) \(model) lightsaber is formed"
33+
}
34+
35+
deinit {
36+
"\(owner?.name ?? "") \(type) \(model) lightsaber is destroyed"
37+
}
38+
}
39+
40+
var lightsaber: Lightsaber?
41+
var yoda: Jedi?
42+
43+
lightsaber = Lightsaber(type: "single blade", model: "Shoto")
44+
yoda = Jedi(name: "Yoda")
45+
46+
yoda?.weapon = lightsaber
47+
lightsaber?.owner = yoda
48+
49+
yoda?.weapon = nil
50+
//lightsaber?.owner = nil
51+
52+
yoda = nil
53+
lightsaber = nil
54+
55+
56+
/*:
57+
Dissection of unowned and weak
58+
*/
59+
60+
// MARK: - Breaking Strong Reference cycle
61+
class JediMaster{
62+
let name: String
63+
weak var weapon: PlasmaLightsaber?
64+
65+
init(name: String) {
66+
self.name = name
67+
"\(name) is a Jedi Master now"
68+
}
69+
70+
deinit {
71+
"\(name) became one with the Force"
72+
}
73+
}
74+
75+
class PlasmaLightsaber{
76+
let type: String
77+
var owner: JediMaster?
78+
79+
init(type: String) {
80+
self.type = type
81+
"The \(type) lightsaber is formed"
82+
}
83+
84+
deinit {
85+
"\(owner?.name ?? "") \(type) lightsaber is destroyed"
86+
}
87+
}
88+
89+
var obwan: JediMaster? = JediMaster(name: "Obi-Wan Kenobi")
90+
var obwanLightsaber: PlasmaLightsaber? = PlasmaLightsaber(type: "single blade")
91+
92+
obwan?.weapon = obwanLightsaber
93+
obwanLightsaber?.owner = obwan
94+
95+
obwan = nil
96+
obwanLightsaber = nil
97+
98+
99+

0 commit comments

Comments
 (0)