Category

How to check if enum case exist under array in swift?

A

Administrator

by admin , in category: Discussion , 4 months ago

You can check if an enum case exists within an array in Swift using the contains() method. Here's how you can do it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
enum MyEnum {
    case case1
    case case2
    case case3
}


let myArray: [MyEnum] = [.case1, .case3]


if myArray.contains(.case2) {
    print("Enum case .case2 exists in the array.")
} else {
    print("Enum case .case2 does not exist in the array.")
}

This will output:

1
Enum case .case2 does not exist in the array.

You simply call the contains() method on the array and pass in the enum case you want to check for. If the case exists in the array, it returns true; otherwise, it returns false.

no answers