Devstoic86
Devstoic86

Reputation: 13

Is there a more idiosyncratic way to write an enum with the same argument types but different cases?

I have an enum such as this:

 enum ValidationMatchingStrategy {
    case contains(pattern: String, error: String? = nil)
    case doesNotContain(pattern: String, error: String? = nil)
    case matches(pattern: String, error: String? = nil)
    case doesNotMatch(pattern: String, error: String? = nil)
}

Depending on the case, I evaluate the associated values differently for regex expressions. However, every case has the same argument type for each and doesn't appear written well. Is there better approach to create this enum?

Upvotes: 1

Views: 57

Answers (1)

Sweeper
Sweeper

Reputation: 273465

Perhaps the enum shouldn't have associated values,

enum ValidationMatchingStrategy {
    case contains
    case doesNotContain
    case matches
    case doesNotMatch
}

And you should create another type, and use composition to combine a ValidationMatchingStrategy, the pattern, and the error:

struct ValidationStrategy {
    let matchingStrategy: ValidationMatchingStrategy
    let pattern: String
    let error: String?
}

Upvotes: 6

Related Questions