Swift Self 作为关联类型绑定在协议中
Swift Self as associated type bound in protocol
我想强制关联类型为 Self
,但编译器有 none 个。
这是我想要编译的内容:
protocol Protocol {
// Error: Inheritance from non-protocol, non-class type 'Self'
associatedtype Type: Self
}
您可能会问,为什么不直接使用 Self
而不是关联类型?仅仅是因为我不能:关联类型是从父协议继承的。在父协议中更改它没有意义。
这与我正在尝试做的类似:
protocol Factory {
associatedtype Type
func new() -> Type
}
protocol SelfFactory: Factory {
associatedtype Type: Self // Same Error
}
编辑:
马特的回答几乎就是我要找的。它在运行时的行为就像我希望的那样,但在编译时限制不够。
我希望这是不可能的:
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
}
}
我希望 Class
中的 typealias
触发重新声明错误或类似错误。
你是想说这个吗?
protocol Factory {
associatedtype MyType
func new() -> MyType
}
protocol SelfFactory: Factory {
func new() -> Self
}
我知道这是一个老问题,但你可以从 Swift 4.0 开始这样做:
protocol Factory {
associatedtype MyType
static func new() -> MyType
}
protocol SelfFactory: Factory where MyType == Self { }
where 子句不是很棒吗?
我想强制关联类型为 Self
,但编译器有 none 个。
这是我想要编译的内容:
protocol Protocol {
// Error: Inheritance from non-protocol, non-class type 'Self'
associatedtype Type: Self
}
您可能会问,为什么不直接使用 Self
而不是关联类型?仅仅是因为我不能:关联类型是从父协议继承的。在父协议中更改它没有意义。
这与我正在尝试做的类似:
protocol Factory {
associatedtype Type
func new() -> Type
}
protocol SelfFactory: Factory {
associatedtype Type: Self // Same Error
}
编辑:
马特的回答几乎就是我要找的。它在运行时的行为就像我希望的那样,但在编译时限制不够。
我希望这是不可能的:
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
}
}
我希望 Class
中的 typealias
触发重新声明错误或类似错误。
你是想说这个吗?
protocol Factory {
associatedtype MyType
func new() -> MyType
}
protocol SelfFactory: Factory {
func new() -> Self
}
我知道这是一个老问题,但你可以从 Swift 4.0 开始这样做:
protocol Factory {
associatedtype MyType
static func new() -> MyType
}
protocol SelfFactory: Factory where MyType == Self { }
where 子句不是很棒吗?