gpt4 book ai didi

Swift:如何在回调闭包中使用 instanceType

转载 作者:行者123 更新时间:2023-11-28 15:05:14 24 4
gpt4 key购买 nike

我想将 self 作为 instancetype 传递给这个函数的回调闭包:

extension UIView {
public func onTap(_ handler: @escaping (_ gesture: UITapGestureRecognizer, _ view: Self) -> Void) -> UITapGestureRecognizer {
...
}
}

let view = UIView.init()
view.onTap { tap, v in
...
}

但是我得到一个错误:

Self' is only available in a protocol or as the result of a method in a class; did you mean 'UIView'?

我该怎么做?

最佳答案

当您可以在 Swift 中非常有效地使用协议(protocol)扩展时,这就是完美的场景(按照书本):

protocol Tappable { }

extension Tappable { // or alternatively: extension Tappable where Self: UIView {
func onTap(_ handler: @escaping (UITapGestureRecognizer, Self) -> Void) -> UITapGestureRecognizer {
return UITapGestureRecognizer() // as default to make this snippet sane
}
}

extension UIView: Tappable { }

然后例如:

let button = UIButton.init()
button.onTap { tap, v in
// v is UIButton...
}

例如:

let label = UILabel.init()
label.onTap { tap, v in
// v is UILabel...
}

等...


注意:您可以阅读有关 Extensions 的更多信息或 ProtocolsSwift Programming Language Book来自 Apple。

关于Swift:如何在回调闭包中使用 instanceType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48559855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com