Ios 试图了解Swift中协议代理的实现
在做了大量的研究之后,我仍然对如何使用和实现委托感到有点困惑。我试着写我自己的,简化的例子,以帮助我的理解-但它不工作-这意味着我一定是有点迷失Ios 试图了解Swift中协议代理的实现,ios,swift,design-patterns,delegates,Ios,Swift,Design Patterns,Delegates,在做了大量的研究之后,我仍然对如何使用和实现委托感到有点困惑。我试着写我自己的,简化的例子,以帮助我的理解-但它不工作-这意味着我一定是有点迷失 //the underlying protocol protocol myRules { func sayName(name: String); } //the delegate that explains the protocols job class myRulesDelegate: myRules { func sayName(
//the underlying protocol
protocol myRules {
func sayName(name: String);
}
//the delegate that explains the protocols job
class myRulesDelegate: myRules {
func sayName(name: String){
print(name);
}
}
//the delegator that wants to use the delegate
class Person{
//the delegator telling which delegate to use
weak var delegate: myRulesDelegate!;
var myName: String!;
init(name: String){
self.myName = name;
}
func useDels(){
//using the delegate (this causes error)
delegate?.sayName(myName);
}
}
var obj = Person(name: "Tom");
obj.useDels();
我已经阅读和观看了很多教程,但我仍然在努力。我不再犯错误了(干杯,伙计们)。但仍然无法从sayName获得任何输出
这说明我一定误解了委托模式的工作原理。
我真的很希望能有一个正确的代码版本,并简单解释它为什么工作,为什么有用
我希望这对其他人也有帮助。干杯。在Swift中,您省略了第一个参数的外部名称,因此您的函数调用应该是
delegate.sayName(“Tom”)
此外,正如您所发现的,为委托
属性使用隐式展开的可选项也是危险的。您应该使用弱可选选项:
//the underlying protocol
protocol MyRulesDelegate: class {
func sayName(name: String)
}
//the delegator that wants to use the delegate
class Person {
//the delegator referencing the delegate to use
weak var delegate: MyRulesDelegate?
var myName: String
init(name: String){
self.myName = name
}
func useDels() {
//using the delegate
delegate?.sayName(myName)
}
}
最后,您的委托必须是一个对象,因此您不能以显示的方式使用委托;您需要创建另一个类,该类可以将自身的实例设置为委托
class SomeOtherClass: MyRulesDelegate {
var myPerson: Person
init() {
self.myPerson = Person(name:"Tom")
self.myPerson.delegate = self
}
func sayName(name: String) {
print("In the delegate function, the name is \(name)")
}
}
var something = SomeOtherClass()
something.myPerson.useDels()
输出:
在委托函数中,名称为Tom
已更正-仍然是问题-检查更新。非常感谢。很抱歉,我出现了一个剪切粘贴错误,其中仍然包含
名称
参数名称。在使用代理之前,您忘记分配它。类似于obj.delegate=myRulesDelegate()
。由于它是隐式展开的可选项,因此会崩溃。见Paulw11的答案。