简体   繁体   English

如何创建一个接受泛型类型作为关联类型的枚举

[英]How to create an enumeration that accepts a generic type as associated type

I'm trying to create an enumeration that accepts a generic type as associated value. 我正在尝试创建一个接受通用类型作为关联值的枚举。
The compiler complains: 编译器抱怨:

Reference to generic type 'GenericItem' requires arguments in <...> 泛型类型'GenericItem'的引用需要<...>中的参数

The scheme is pretty simple: 该方案非常简单:

struct GenericItem <Item:FormattableAsStringWithPrecision> {
    let value: Item
}

enum Enumeration {
    case Generic(values: [GenericItem])
}

I can't understand how to make this possible. 我不明白如何做到这一点。

You need to add the Generic type to the enum too, the types can be inferred from the initialiser so you do not need to pass it as a generic type argument. 您还需要将泛型类型添加到枚举,可以从初始化程序中推断类型,因此您无需将其作为泛型类型参数传递。

Below is an example of how you might do it. 以下是如何执行此操作的示例。

struct GenericItem<T: CustomDebugStringConvertible> {
  let value: T
}

enum Enumeration<T: CustomDebugStringConvertible> {
  case Generic(value: [GenericItem<T>])
}

let someValue = Enumeration.Generic(value: [ GenericItem(value: "") ])

edit: I changed the FormattableAsStringWithPrecision to CustomDebugStringConvertible as I assumed it was one of your own custom protocols which can be easily swapped out, but the same logic would still apply for any protocol. 编辑:我改变了FormattableAsStringWithPrecisionCustomDebugStringConvertible ,因为我认为那是可以很容易地换出自己的自定义协议之一,但同样的逻辑仍然适用于任何协议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM