Skip to content

Commit ab043d9

Browse files
author
Bob Lee
committed
Added delegate
1 parent 37d2f3b commit ab043d9

File tree

4 files changed

+27
-9
lines changed

4 files changed

+27
-9
lines changed
0 Bytes
Binary file not shown.

source-code/4000_protocol_oriented_swift/4004_delegate.playground/Contents.swift

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@
44
### Protocol Oriented Swift
55
### Delegate
66

7-
**Problem:** Communicate between classes and structs
7+
**Problem:** How does delegate even work?
88

99
---
1010
*/
11-
//: Delegate
12-
//: 1. A gift from Apple engineers
13-
//: 2. microwave analogy
11+
12+
//: > **Purpose of Delegate:** Communicate between objects
13+
14+
15+
//: **Goal:** Send data from `FirstVC` to `SecondVC`
1416

1517
//: Design Protocol
1618
protocol PassDataDelegate {
@@ -20,16 +22,17 @@ protocol PassDataDelegate {
2022

2123
//: Design Delegator (Sender)
2224
class FirstVC {
25+
func drawCircle() {}
2326
var delegate: PassDataDelegate?
2427
}
2528

26-
FirstVC().delegate?.passData(data: "Bob")
29+
FirstVC().delegate?.passData(data: "A bunch of contracts")
2730

2831

2932
//: Design Delegate (Receiver)
3033
class SecondVC: PassDataDelegate {
3134
func passData(data: String) {
32-
print("Something happened")
35+
print("The CEO gave me \(data)")
3336
}
3437
}
3538

@@ -40,17 +43,32 @@ let secondVC = SecondVC()
4043

4144
//: Assign Delegate
4245
firstVC.delegate = secondVC
43-
firstVC.delegate?.passData(data: "Hello, 1231231")
44-
46+
firstVC.delegate?.passData(data: "A bunch of contracts")
4547

4648

4749

4850

51+
//: Practical Example in iOS
52+
import UIKit
4953

54+
class BobViewController: UIViewController, UITableViewDelegate {
55+
let tableView = UITableView()
56+
override func viewDidLoad() {
57+
super.viewDidLoad()
58+
tableView.delegate = self
59+
}
60+
61+
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
62+
print(indexPath)
63+
}
64+
}
5065

5166

67+
//: tableView.delegate.tableView(_ tableView: UITableView, didSelectRorwAt indexPath: IndexPath)
5268

5369

70+
// UITableView is the delegator/CEO/sender
71+
// BobViewController is the delegate/Secretary/receiver
5472

5573

5674

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2-
<playground version='5.0' target-platform='ios' display-mode='raw'>
2+
<playground version='5.0' target-platform='ios' display-mode='rendered'>
33
<timeline fileName='timeline.xctimeline'/>
44
</playground>
1.73 KB
Binary file not shown.

0 commit comments

Comments
 (0)