【问题标题】:Trying to understand the implementation of delegates with protocols in Swift试图理解 Swift 中使用协议的委托的实现
【发布时间】:2016-08-05 10:12:44
【问题描述】:

经过大量研究后,我仍然对如何使用和实现委托感到有些困惑。我已经尝试编写自己的简化示例来帮助我理解 - 但是它不起作用 - 这意味着我一定有点迷茫。

//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 得到任何输出。

这表明我一定误解了委托模式的工作原理。 我真的很感谢代码的更正版本,并简单解释了它的工作原理以及它为什么有用。

我希望这对其他人也有帮助。干杯。

【问题讨论】:

  • 您在使用之前忘记分配代理。喜欢obj.delegate = myRulesDelegate()。而且由于它是一个隐式展开的可选项,它会崩溃。请参阅 Paulw11 的回答。

标签: ios swift design-patterns delegates


【解决方案1】:

在 Swift 中你省略了第一个参数的外部名称,所以你的函数调用应该是delegate.sayName("Tom")

此外,正如您所发现的那样,为您的 delegate 属性使用隐式展开的可选选项是危险的。你应该使用一个弱可选:

//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

【讨论】:

  • 已更正 - 仍然是一个问题 - 检查更新。非常感谢。
  • 抱歉,我遇到了剪切和粘贴错误,我仍然包含 name 参数名称
猜你喜欢
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2015-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多