swift - 如何为一组字符串枚举定义一个公共(public)接口(interface),以供另一个类互换使用

标签 swift enums interface

我想做这个或类似的事情来获得相同的功能 有人可以帮忙吗?

protocol FilterEnum: CaseIterable {
}

enum SomeFilterEnum: String, FilterEnum {
   case owner = "Owner"
   case karat = "Karat"
}

class SomeCls {
    private let filterTypes: [FilterEnum]

    init(filterTypes: [FilterEnum]){
        self.filterTypes = filterTypes
    }

    func useFilterTypes() {
       for type in filterTypes{
           print(type.rawValue)
        }
    }
}

let sm = SomeCls(filterTypes: SomeFilterEnum.allCases)

最佳答案

从你的用法来看,你需要这个通用接口(interface)既是CaseIterable又是RawRepresentable。好吧,那是 CaseIterable & RawRepresentable,但我们不能直接将其用作类型,因为它们都有关联类型。我们必须在 SomeCls 上引入一个通用参数:

class SomeCls<T> where T : CaseIterable & RawRepresentable, T.RawValue == String {
    private let filterTypes: [T]

    init(filterTypes: [T]){
        self.filterTypes = filterTypes
    }

    func useFilterTypes() {
        for type in filterTypes{
            print(type.rawValue)
        }
    }
}

关于swift - 如何为一组字符串枚举定义一个公共(public)接口(interface),以供另一个类互换使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57737866/

相关文章:

c# - 为什么要从 Unity 委托(delegate)事件中删除事件?

swift - NSOutlineview 奇怪的行为

ios - Swift 2.0 'unexpected trailing closure' 惰性变量分配错误

python - Postgres/SQLAlchemy/Alembic 将数据类型从 enum 更改为 int 并使用 map 值

.net - IEnumerable & IEnumerator

java - 我应该如何组织这段代码(OOP,接口(interface))

ios - 如何将此 Web 服务方法声明为全局方法?

swift - 隐藏节点不显示带有名称的子节点

C# 重载枚举来存储值

swift - 在 Swift 中比较枚举