Swift: Adding parameter to protocol function

限于喜欢 提交于 2019-12-12 02:44:43

问题


Consider the following code, which prints "working" when a button is pressed:

protocol MyClassDelegate: class {
    func foo()
}

class MyClass {

    weak var delegate: MyClassDelegate?

    func foo() {
        delegate?.foo()
    }

    let button: UIButton = {
        button.addTarget(self, action: #selector(foo), for: .touchUpInside)
        return button
    }()
}

class MyViewController { ... }

extension MyViewController: MyClassDelegate {
    func foo() {
        print("working")
    }
}

When I try adding a parameter to MyClassDelegate's foo method, "working" stops printing (meaning the button stops working?). I.e.:

protocol MyClassDelegate: class {
    func foo(_ str: String)
}

class MyClass {

    weak var delegate: MyClassDelegate?

    func foo() {
        delegate?.foo("working")
    }

    let button: UIButton = {
        button.addTarget(self, action: #selector(foo), for: .touchUpInside)
        return button
    }()
}

class MyViewController { ... }

extension MyViewController: MyClassDelegate {
    func foo(_ str: String) {
        print(str)
    }
}

How can I get the second version of the code with the parameter to work? Thanks.


回答1:


You are calling a wrong method on the delegate . Your MyClassDelegate doesn't have method named showDetails() . Call your delegate method this way:

 func foo() {
    delegate?.foo("working")
  }



回答2:


The problem was that button needs to be a declared with lazy var rather than with let.




回答3:


Did you do that: cell.delegate = self in your ViewController?



来源:https://stackoverflow.com/questions/43928901/swift-adding-parameter-to-protocol-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!