[英]Swift protocol that is using an enum with generic associated type
我正在嘗試創建一個快速使用通用枚舉的協議。 編譯器將引發此錯誤: Protocol can only be used as a generic constraint because it has associated type requirements
短代碼片段:
enum GenericEnum<T> {
case Unassociated
case Associated(T)
}
protocol AssociatedProtocol {
typealias AssociatedType
func foo() -> GenericEnum<AssociatedType>
}
let bar = [AssociatedProtocol]()
您可以在此處找到更長的示例。
有人知道該問題的解決方案嗎?
問題出在這里:想象一下后續的代碼行。
// none of this will compile...
var bar = [AssociatedProtocol]()
bar.append(GenericEnum.Associated(1))
bar.append(GenericEnum.Associated("hello")
let foo = bar[0].foo()
foo
是什么類型? 是GenericEnum<Int>
還是GenericEnum<String>
? 還是沒有?
這尤其是一個問題,因為枚舉與結構一樣都是“值類型”。 這意味着它們的大小取決於它們所包含的內容。 采取以下代碼:
let x = GenericEnum.Associated(1)
sizeofValue(x) // 9 - 1 byte for the enum, 8 for the Int
let y = GenericEnum.Associated("hello")
sizeofValue(y) // 25 - 1 byte for the enum, 24 for the String
帶有關聯類型的協議實際上只是在約束通用功能。 所以這很好:
func f<T: AssociatedProtocol>(values: [T]) {
var bar = [T]() // T is an instance of a specific
// AssociatedProtocol where T.AssociatedType
// is fixed to some specific type
}
但是單獨使用它是沒有意義的(至少對於當前的Swift版本1.2 –新功能可能會啟用該版本中的其他功能)。
如果您需要在運行時動態多態使用協議,則需要放棄類型別名。 然后,它可以用作固定大小的參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.