今、友人と詳解Swiftを読んでるのですが、protocolの勉強をしたので iOSのUIKitなどで多用されているdelegateパターンをどう実装するのか試してみました。
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
class Bracer {
var delegate : BracerDelegate?
func addBrace() -> String {
if let outText = delegate?.description() {
return "{ \(outText) }"
}
return "{}"
}
func addClientBrace() -> String {
let brace = delegate?.clientBrace ?? ("[", "]")
if let outText = delegate?.description() {
return "\(brace.0) \(outText) \(brace.1)"
}
return "\(brace.0)\(brace.1)"
}
}
protocol BracerDelegate {
var clientBrace : (String, String) { get set }
func description() -> String
}
class BracerClient : BracerDelegate {
var text : String
var clientBrace = ("<", ">")
init(string: String) {
text = string
}
func description() -> String {
return text
}
func printWithBrace() {
let bracer = Bracer()
bracer.delegate = self
println(bracer.addBrace())
}
func printWithMyBrace() {
let bracer = Bracer()
bracer.delegate = self
println(bracer.addClientBrace())
}
}
let bc1 = BracerClient(string: "sample code")
bc1.printWithBrace()
bc1.printWithMyBrace()
bc1.clientBrace = ("<%", "%>")
bc1.printWithMyBrace()