在尝试创建我的抽象时:
protocol ElectricallyDrawable {
func isConnected() -> Bool
func showPowerAnimation(using shape: Shape) <-- Error
}
Protocol 'Shape' can only be used as a generic constraint because it has Self or associated type requirements
首先,我知道这个问题已经被问了次。
我理解这个错误,如果我知道Shape
有associatedtype
,我会预料到的。。
所以。。
我不是在问我为什么会出现这个错误
我的问题是:
如何计算每个protocol
的associatedtype
因为我已经搜索了文档和定义,什么都没有。
如果我们知道associatedtype
命名法,那么我们可以将其设置为我们的具体类型。。例如
如果我知道:
protocol Shape {
associatedtype Line
}
然后我可以像这样使用它:
protocol ElectricallyDrawable {
typealias Line = Rectangle <-- This would stop the error
func isConnected() -> Bool
func showPowerAnimation(using shape: Shape)
}
所以我要回答两个问题
1(您应该如何获得协议的associatedtype
有两种选择。选项a:您正在实现接口:
struct Resistor: ElectricallyDrawable {
typealias Line = Rectangle
}
在这种情况下,很明显,你的线是一个矩形,因为你定义了它
选项b:您正在扩展接口:
extension ElectricallyDrawable where Line == Rectangle {
//...
}
或
extension ElectricallyDrawable {
func x() {
if Line.self == Rectangle.self {
//...
}
}
}
因此,无论哪种方式,您都只需通过名称"获取"associatedtype
。
2(你实际上会怎么做
有两种选择。你可以这样走associatedtype
:
protocol ElectricallyDrawable {
associatedtype Line: Shape
func isConnected() -> Bool
func showPowerAnimation(using shape: Line)
}
当你约束自己associatedtype
(你正在使用的实际类型(是一个形状时,或者你为函数本身添加了一个泛型:
protocol ElectricallyDrawable {
func isConnected() -> Bool
func showPowerAnimation<S>(using shape: S) where S: Shape
}
任何一种方法都可以,最好的方法可能取决于您的用例