[swift-evolution] Testing enum cases with associated values
Rien
Rien at Balancingrock.nl
Wed Jan 18 00:53:32 CST 2017
A guy named Matthias recently commented this on my blog:
func == (left: Enum3, right: Enum3) -> Bool {
switch (left, right) {
case (.ONE, .ONE):
return true
case (.TWO(let str1), .TWO(let str2)):
return str1 == str2
default:
return false
}
}
http://swiftrien.blogspot.nl/2015/05/swift-enum-compare-design-pattern.html
Regards,
Rien
Site: http://balancingrock.nl
Blog: http://swiftrien.blogspot.com
Github: http://github.com/Swiftrien
Project: http://swiftfire.nl
> On 18 Jan 2017, at 01:15, Andy Chou via swift-evolution <swift-evolution at swift.org> wrote:
>
> Enums with associated values can be very useful in Swift, but once you add associated values you lose some properties, especially equality:
>
> ```
> enum AuthenticationResponse {
> case success
> case alert(Alert)
> case reauthenticate
> }
> ```
>
> Testing for a specific case requires a switch statement or the if pattern match syntax:
>
> if case .success = response { … }
>
> But while this works well for control flow, it doesn’t work well for cases where we want a Bool, such as assert(). There are also common situations with lists and libraries like RxSwift where a filtering function uses a Bool valued closure. In these situations the best we can do is write functions like:
>
> ```
> enum AuthenticationResponse {
> case success
> case alert(Alert)
> case reauthenticate
>
> var isSuccess: Bool {
> if case .success = self {
> return true
> } else {
> return false
> }
> }
>
> var isReauthenticate: Bool {
> if case .reauthenticate = self {
> return true
> } else {
> return false
> }
> }
>
> var isAlert: Bool {
> if case .alert(_) = self {
> return true
> } else {
> return false
> }
> }
> }
> ```
> Any suggestions better than writing out each of these functions explicitly?
>
> The conditional conformances proposal coming in Swift 4 solves some of this issue, but not completely. If Alert isn’t Equatable, it is still useful to test whether the result is .success. For example:
>
> assert(response == .success)
>
> This is perfectly intelligible and I would argue that equality should be defined for enums with associated values omitted:
>
> assert(response == .alert)
>
> Here we are ignoring the associated values, and merely checking if the enum case is the same.
>
> Andy
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
More information about the swift-evolution
mailing list