Swift协议正在使用具有通用关联类型的枚举 [英] Swift protocol that is using an enum with generic associated type
问题描述
我正在尝试创建一个在swift中使用通用枚举的协议。
编译器抛出此错误:协议只能用作通用约束,因为它具有相关类型要求
短代码剪辑:
枚举GenericEnum< T> {
case Unassociated
case Associated(T)
}
协议AssociatedProtocol {
typealias AssociatedType
func foo() - > GenericEnum< AssociatedType>
}
let bar = [AssociatedProtocol]()
您可以在此处找到更长的示例。
<有没有人知道这个问题的解决方案?
以下是问题:想象一下后续的代码行。 >
//这些都不会编译...
var bar = [AssociatedProtocol]()
bar.append (GenericEnum.Associated(1))
bar.append(GenericEnum.Associated(hello)
let foo = bar [0] .foo()
什么类型是 foo
?它是一个 GenericEnum< Int& / code>或$ code> GenericEnum< String>
?还是两者?
这是一个特别的问题,因为枚举,像结构体,是值类型,这意味着它们的大小取决于它们的含义。使用以下代码:
let x = GenericEnum.Asso ciated(1)
sizeofValue(x)//枚举为9 - 1个字节,8为Int
let y = GenericEnum.Associated(hello)
sizeofValue(y)/ / 25 - 1个字节为枚举,24为字符串
协议与相关类型只是真的在那里限制通用功能。所以这样会很好:
func f< T:AssociatedProtocol>(values:[T]){
var bar = [T]()// T是特定
// AssociatedProtocol的一个实例,其中T.AssociatedType
//固定为某个特定类型
}
但使用它独立是没有意义的(至少与目前的1.2版本的Swift - 新功能可能会启用
如果您需要在运行时多态动态使用该协议,则需要使用typealias。然后,它可以用作固定大小的引用。
I'm trying to create a protocol that is using a generic enum in swift.
The compiler throws this error: Protocol can only be used as a generic constraint because it has associated type requirements
Short code snipped:
enum GenericEnum<T> {
case Unassociated
case Associated(T)
}
protocol AssociatedProtocol {
typealias AssociatedType
func foo() -> GenericEnum<AssociatedType>
}
let bar = [AssociatedProtocol]()
You can find a longer example here.
Does anybody know a solution to that issue?
Here’s the problem: imagine some subsequent lines of code.
// none of this will compile...
var bar = [AssociatedProtocol]()
bar.append(GenericEnum.Associated(1))
bar.append(GenericEnum.Associated("hello")
let foo = bar[0].foo()
What type is foo
? Is it a GenericEnum<Int>
or a GenericEnum<String>
? Or neither?
This is especially a problem because enums, like structs, are "value types". That means their size is determined by what they contain. Take the following code:
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
Protocols with associated types are only really there to constrain generic functions. So this would be fine:
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
}
but to use it stand-alone doesn’t make sense (at least with the current version 1.2 of Swift – new features might enable other things in the version).
If you need the protocol to be used polymorphically dynamically at runtime, you would need to ditch the typealias. Then instead it can be used as a fixed-size reference.
这篇关于Swift协议正在使用具有通用关联类型的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!