[英]Swift Self as associated type bound in protocol
我想強制關聯類型為Self
,但編譯器沒有它。
這是我想要編譯的內容:
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
}
編輯:
matt的答案幾乎就是我要找的。 它的行為就像我想要的那樣在運行時,但在編譯時不夠嚴格。
我希望這是不可能的:
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 { }
不是哪里的條款好嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.