Thi*_*aos 4 generics type-constraints associated-types swift
我想强制关联类型为Self
,但编译器没有。
这是我想要编译的内容:
protocol Protocol {
// Error: Inheritance from non-protocol, non-class type 'Self'
associatedtype Type: Self
}
Run Code Online (Sandbox Code Playgroud)
你可能会问,为什么不直接使用Self
而不是关联类型呢?仅仅因为我不能:关联类型是从父协议继承的。在父协议中更改它没有意义。
这是类似于我正在尝试做的事情:
protocol Factory {
associatedtype Type
func new() -> Type
}
protocol SelfFactory: Factory {
associatedtype Type: Self // Same Error
}
Run Code Online (Sandbox Code Playgroud)
编辑:
马特的答案几乎就是我要找的。它的行为就像我希望它在运行时一样,但在编译时不够严格。
我希望这是不可能的:
protocol Factory {
associatedtype MyType
static func new() -> MyType
}
protocol SelfFactory: Factory {
static func new() -> Self
}
final class Class: SelfFactory {
// Implement SelfFactory:
static func new() -> Class {
return Class()
}
// But make the Factory implementation diverge:
typealias MyType = Int
static func new() -> Int {
return 0
}
}
Run Code Online (Sandbox Code Playgroud)
我希望typealias
inClass
触发重新声明错误或类似错误。
我意识到这是一个老问题,但是您可以从Swift 4.0 开始执行此操作:
protocol Factory {
associatedtype MyType
static func new() -> MyType
}
protocol SelfFactory: Factory where MyType == Self { }
Run Code Online (Sandbox Code Playgroud)
where 子句不是很好吗?
归档时间: |
|
查看次数: |
1511 次 |
最近记录: |