简体   繁体   中英

Compare Swift enum regardless of the associated value

Is it somehow possible to test an enum case regardless of the associated value ?

enum Abc {
    case A(a:Int)
    case B(b:Int)
}

let a = Abc.A(a:1)

a == Abc.A  // <= Not possible 

Sure, you can do this in a switch :

switch a {
case .A:
    print("it's A")
default:
    print("it's not A")
}

Or use pattern matching in an if statement:

if case .A = a {
    print("it's A")
} else {
    print("it's not A")
}

If you're still interested in the associated value after matching the case, you can extract it like so:

switch a {
case .A(let value):
    ...
}

if case .A(let value) = a {
    ...
}

Note @overactor's comment below that you can also write this as case let .A(value) – it's mainly a matter of personal preference.

You can use an if case

enum ABC {
    case A(a: Int)
    case B(b: Int)
}

let a = ABC.A(a: 1)

if case .A = a {
    ...
}

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