本文介绍了Swift:将参数添加到协议功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码,当按下按钮时,该代码将显示正在工作
:
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")
}
}
当我尝试向 MyClassDelegate
的 foo
方法,正在工作
停止打印(意味着按钮停止工作?)。即:
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.
推荐答案
问题是 button
需要声明使用 lazy var
而不是使用 let
。
The problem was that button
needs to be a declared with lazy var
rather than with let
.
这篇关于Swift:将参数添加到协议功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!