Reputation: 98
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])
Upvotes: 2
Views: 1141
Reputation: 41
You can use static functions to mimic cases with variadic argument:
enum ModelRule {
case required(keys: [String])
case nonEmptyString(keys: [String])
case emptyString(key: String)
static func required(keys: String...) -> Self {
.required(keys: keys)
}
static func nonEmptyString(keys: String...) -> Self {
.nonEmptyString(keys: keys)
}
}
Usage:
ruleChecker.apply(rule: .required(keys: "a", "b", "c"))
Upvotes: 4
Reputation: 6600
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")
Upvotes: 5
Reputation: 4226
Variadic parameter used to work on swift 4 but it wasn't intentionally. Just use arrays
enum ModelRule {
case required(keys: [String])
case nonEmptyString(keys: [String])
case emptyString(key: String)
}
Upvotes: 3