“不支持可变的枚举类型” Swift 5错误

时间:2019-05-31 14:15:43

标签: swift swift5

以下代码中出现# TYPE DATABASE USER IP-ADDRESS METHOD host all all 127.0.0.1 md5 错误。在Swift4中可以正常编译和运行,但是在Swift5,Xcode 10.2中却给出了编译时错误

Variadic enum cases are not supported

虽然信息很明确,但我想知道为什么他们会删除完美的功能?还是我在这里想念东西?

此外,有没有比跟随错误更好的解决方案了? enum ModelRule { case required(keys: String...) // error: Variadic enum cases are not supported case nonEmptyString(keys: String...) // error: Variadic enum cases are not supported case emptyString(key: String) }

2 个答案:

答案 0 :(得分:1)

可变参数曾经在swift 4上起作用,但不是故意的。 只需使用数组

enum ModelRule {
    case required(keys: [String])
    case nonEmptyString(keys: [String])
    case emptyString(key: String)
}

请参见Swift Release notes

答案 1 :(得分:1)

扩展评论:

您应该在案例的关联值中具有数组。但是为了方便起见,请创建带有可变参数的方法。

示例:

enum ModelRule {
    case required(keys: [String])
    case nonEmptyString(keys: [String])
    case emptyString(key: String)

    init(required keys: String...) { // It could be static func, but init here works and looks better
        self = .required(keys: keys)
    }

    init(nonEmptyString keys: String...) {
        self = .nonEmptyString(keys: keys)
    }

    init(emptyString key: String) { // Added this just for my OCD, not actually required
        self = .emptyString(key: key)
    }
}

用法:

let required = ModelRule(required: "a", "b", "c") // .required(keys: ["a", "b", "c"])
let nonEmpty = ModelRule(nonEmptyString: "d", "e", "f") // .nonEmptyString(keys: ["d", "e", "f"])
let empty = ModelRule(emptyString: "g") // .emptyString(key: "g")