在Swift中,如何在协议扩展中使用通用枚举类型?

策克尔

我想在它们之间共享功能CatZooDogZoo因为它们在后台存储相似的数据,但我也希望他们知道它们是什么,以便它们可以对特定数据进行操作,如DogZoo.makeNoise()方法所示

正确的类型是AnimalStorageProtocol.storage什么?

enum CatType: String {
    case lion
    case tiger
    case panther
}

enum DogType: String {
    case coyote
    case domestic
    case wolf
}

struct CatZoo: AnimalStorageProtocol {
    private var storage: [CatType: Int] // it's a bonus if they can stay private
}

struct DogZoo: AnimalStorageProtocol {
    private var storage: [DogType: Int]

    func makeNoise() {
        for (key, value) in storage {
            switch key  {
            case .coyote:
                print("\(value) yips!")
            case .domestic:
                print("\(value) barks!")
            case .wolf:
                print("\(value) howls!")
            }
        }
    }
}

我以为可以在协议中定义泛型枚举类型但无法使其正常工作。

protocol AnimalStorageProtocol {
    // var storage: <RawRepresentable where RawRepresentable.RawValue == String: Int> { get set }
    var storage: [RawRepresentable: Int] { get set }
}

extension AnimalStorageProtocol {
    var isEmpty: Bool {
        get {
            for (_, value) in storage {
                if value != 0 {
                    return false
                }
            }
            return true
        }
    }
}
克雷格·西门子

您可以根据需要使用两种不同的方法。


如果您不需要将类型设为枚举,则只需执行

protocol AnimalStorageProtocol {
    associatedtype AnimalType: Hashable
    var storage: [AnimalType: Int] { get set }
}

这将允许使用任何可哈希类型。


如果您要求类型只能位于aRawRepresentable所在的位置,RawValueString必须定义动物类型必须符合的另一种协议。

protocol AnimalType: Hashable, RawRepresentable {
    var rawValue: String { get }
}

protocol AnimalStorageProtocol {
    associatedtype Animal: AnimalType
    var storage: [Animal: Int] { get set }
}

然后,您只需要设置您的枚举类型以符合AnimalType协议即可。

enum CatType: String, AnimalType { ... }
enum DogType: String, AnimalType { ... }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在协议中使用通用Swift枚举

如何在通用函数中使用Swift通用Decodable协议

如何在Swift中使通用枚举相等

如何在CodingKeys枚举(可编码协议)中使用通用值

如何在Swift协议中定义枚举

如何在Swift中创建通用协议?

在Swift扩展中将通用类型与协议兼容

如何在Swift中扩展协议

我如何在 Swift 5 中使用协议函数参数使用关联类型的协议(即 .pickerStyle())

具有通用枚举和通用协议的Swift类型擦除

如何在Swift中构造通用类型协议一致性?

如何在Swift扩展中使用包装器类型参数

如何在Swift中使用带有关联类型的协议关闭时使用Void类型

如何要求通用类型使用协议中的特定类型来实现通用协议

如何在Swift中使用扩展协议在Obj-C类上公开现有属性

如何在方法签名中使用通用协议?

如何在Swift中确认可识别协议的枚举?

如何在使用关联类型的协议中使用类型擦除

如何在Swift中将具有关联类型的协议(通用协议)作为参数传递?

数组中的Swift通用协议类类型

协议和通用类型中的Swift typealias

如何在协议扩展中使用#selector(myMethodName)?

如何在where子句中使用协议扩展

如何在Swift中的协议扩展中覆盖实例方法?

在协议中使用通用方法Swift

在Swift中使用通用协议实现委托

如何使用具有关联类型的协议初始化通用枚举?

Swift协议可选函数中如何使用枚举作为参数

如何在Swift中覆盖协议扩展的计算属性