Search code examples
swiftswift5

"Variadic enum cases are not supported" swift 5 error


I am getting Variadic enum cases are not supported error in following code. This was compiling and working fine in Swift4, but giving compile time error in Swift5, Xcode 10.2

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

while the message is very clear, I would like to know why would they remove perfectly working feature? Or am I missing something here?

Also, is there any better solution to above error than following ? case required(keys: [String])


Solution

  • Expanding the comment:

    You should have arrays in associated values of cases. But for convenience create methods with variadic parameters.

    Example:

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

    Usage:

    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")