首页 > 解决方案 > 编写一个泛型函数以从 Swift 中的多个枚举中获取公共变量

问题描述

我想编写一个可以访问多个枚举案例及其公共变量的通用方法。

    enum MyEnum:String,CaseIterable {
        case a = "a"

        var ourVar:MyAnotherEnum {
            switch self {
            case .a:
                return MyAnotherEnum.a1
            }
        }
    }

    enum MyAnotherEnum:String,CaseIterable {
        case a1 = "a1"
    }


    enum YourEnum:String,CaseIterable {
        case b = "b"

        var ourVar:YourAnotherEnum {
            switch self {
            case .b:
                return YourAnotherEnum.b1
            }
        }
    }

    enum YourAnotherEnum:String,CaseIterable {
        case b1 = "b1"
    }

我和你的枚举都具有“ourVar”作为常见。现在,我想编写一个方法,如果我传递一个枚举,它可以打印所有值。像这样的东西:

printAll(MyEnum.self) //Should print "a" and "a1"

我试着像迭代一个枚举一样:

    func printAll<T>(_ id:T.Type) where T:RawRepresentable, T:CaseIterable {
        for c in T.allCases {
            print(c.rawValue) //Prints the value correctly
            print(c.ourVar) //Throws error "Value of type 'T' has no member 'ourVar'"
        }
    }

我的确切期望是,printAll(myEnum)应该打印“a”和“a1”。

我的代码流解释起来很复杂,但我绝对需要这种方法来节省数千行代码。任何人都可以帮助我吗?

标签: swiftvariablesgenericsenums

解决方案


首先,您需要创建一个CommonEnum protocolwithourVar作为这样的要求之一,

protocol CommonEnum {
    associatedtype T
    var ourVar: T { get }
}

protocol现在符合上述MyEnumYourEnum,

enum MyEnum: String, CaseIterable, CommonEnum {
    //....
}


enum YourEnum: String,CaseIterable, CommonEnum {
    //....
}

接下来,printAll(_:)方法将是

func printAll<T>(_ id: T.Type) where T: CommonEnum & RawRepresentable & CaseIterable {
    for c in T.allCases {
        print(c.rawValue)
        print(c.ourVar)
    }
}

例子:

printAll(MyEnum.self) //prints a and a1

推荐阅读