【发布时间】:2020-06-22 01:18:13
【问题描述】:
我是 Swift 新手,我很难理解将 self 分配给代表的目的。部分困难源于委托似乎以两种不同的方式使用。
首先是在特定事件发生时将消息从一个类发送到另一个类的方法,类似于状态管理。其次是使“一个类或结构能够将其某些职责移交(或委托)给另一种类型的实例”,如documentation 中所述。我有一种感觉,这两者本质上是相同的,我只是不明白。
protocol PersonProtocol {
func getName() -> String
func getAge() -> Int
}
class Person {
var delegate: PersonProtocol?
func printName() {
if let del = delegate {
print(del.getName())
} else {
print("The delegate property is not set")
}
}
func printAge() {
if let del = delegate {
print(del.getAge())
} else {
print("The delegate property is not set")
}
}
}
class ViewController: UIViewController, PersonProtocol {
var person: Person!
override func viewDidLoad() {
person.delegate = self
person.printAge()
person.printName()
}
func getAge() -> Int {
print("view controller")
return 99
}
func getName() -> String {
return "Some name"
}
}
在这种情况下person.delegate = self 的目的是什么?没有它,ViewController 不是已经需要符合 PersonProtocol 了吗?
【问题讨论】:
标签: ios swift delegates swift-protocols