gpt4 book ai didi

ios - swift 5。协议(protocol)扩展引发编译错误 'Cannot invoke function with an argument list of type Self'

转载 作者:行者123 更新时间:2023-11-28 11:35:18 27 4
gpt4 key购买 nike

我想实现某种 Decorator模式,允许编写可重用装饰器

所以我定义了2个协议(protocol)。第一个定义装饰器的类型:

    protocol ViewDecorator {
associatedtype View: Decoratable
func decorate(view: View)
}

// this is how I expect to use decorator
class GreenViewDecorator: ViewDecorator {
typealias View = GreenView

func decorate(view: GreenView) {
view.backgroundColor = UIColor.green
}
}

第二个定义了一个 decoratable View 应该符合的类型。

    protocol Decoratable {
func decorate<T: ViewDecorator>(with decorator: T)
}

extension Decoratable where Self: UIView {
func decorate<T : ViewDecorator>(with decorator: T) {
decorator.decorate(view: self)
}
}

// exampled of 'decoratable' view
class GreenView: UIView, Decoratable { }

我定义了函数的默认实现 func decorate<T : ViewDecorator>(with decorator: T)在协议(protocol)扩展中。我发现如果我的 View 默认实现该方法是很有用的。我只需要它只继承Decoratable协议(protocol)。然后我可以像这样使用它:

    // example of using decorator with view
let decorator = GreenViewDecorator()
greenView.decorate(with: decorator)

但 Swift5 编译器在 decorator.decorate(view: self) 行引发错误

Cannot invoke 'decorate' with an argument list of type '(view: Self)'

Compilation error

============== TOTAL LISTING ==========
protocol ViewDecorator {
associatedtype View: Decoratable
func decorate(view: View)
}

protocol Decoratable {
func decorate<T: ViewDecorator>(with decorator: T)
}

extension Decoratable where Self: UIView {
func decorate<T : ViewDecorator>(with decorator: T) {
decorator.decorate(view: self)
}
}

class GreenView: UIView, Decoratable { }

class GreenViewDecorator: ViewDecorator {
typealias View = GreenView

func decorate(view: GreenView) {
view.backgroundColor = UIColor.green
}
}

class ViewController: UIViewController {
@IBOutlet var greenView: GreenView!

override func viewDidLoad() {
super.viewDidLoad()
let decorator = GreenViewDecorator()
greenView.decorate(with: decorator)
}
}

最佳答案

参数的类型是关联类型 View,但尚未在任何地方确定 Self 是该类型,因此您不能传递 类型的参数code>Self 没有确定它是兼容的。例如:

extension Decoratable where Self: UIView {
func decorate<T: ViewDecorator>(with decorator: T) where T.View == Self {
decorator.decorate(view: self)
}
}

(但是,如果您这样做,您将难以遵守 Decoratable 协议(protocol),因为它需要此方法用于任何 ViewDecorator。您可以更改协议(protocol)以也具有相同的 T.View == Self 限制。)

关于ios - swift 5。协议(protocol)扩展引发编译错误 'Cannot invoke function with an argument list of type Self',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55591552/

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