简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM