swift - 在 Swift 中,如何在协议(protocol)扩展中使用通用枚举类型?

标签 swift enums

我想在 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!")
            }
        }
    }
}

我想我可以定义一个通用枚举类型 in the protocol但我没能让它发挥作用。

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 }
}

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


如果您要求类型只能是 RawRepresentable,其中 RawValueString,您必须定义您的另一个协议(protocol)动物类型必须符合。

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

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

然后您只需设置枚举类型以符合 AnimalType 协议(protocol)。

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

关于swift - 在 Swift 中,如何在协议(protocol)扩展中使用通用枚举类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44684576/

相关文章:

swift - 如何将我的分数变量发送到另一个 View Controller ?

Java 枚举...它们是在哪里创建的?

java - 枚举继承,或类似的东西

c++ - 如何将无符号整数分配给 C++ 中的枚举?

swift - 尝试更新将返回 : fatal error: unexpectedly found nil while unwrapping an Optional value 的 do-catch block 中的变量

swift - 从 NSTimeInterval 转换为天

安卓头?如何创建在整个项目中可见的枚举?

java - 枚举实现接口(interface)、接口(interface)和方法可见性

ios - 我无法让这个 CA 动画正常工作

ios - Swift 4 - 如何在核心数据中保存 NSAttributedstring