You can easily create a function that works for specific enum
s, however, creating a generic assert function that works for any enums will be quite hard to achieve, because there's no protocol/type constraint that could represent any enum
. You can use RawRepresentable
for enums with raw values, but that won't cover all enum
s, such as the one in your question.
This is the function for your specific enum.
func XCTAssertEnumCase(_ testValue: MyEnum, _ expectedValue: MyEnum) -> Bool {
switch (testValue, expectedValue) {
case (.firstCase, .firstCase):
return true
case (.secondCase, .secondCase):
return true
default:
return false
}
}
Alternatively, you can make your enum conform to Equatable
in your test target (if it doesn't already conform in your actual production target) and only check case equality in your Equatable
conformance, but then you won't be able to easily test "full equality" (including the associated values). Also, the solution will require you to manually implement Equatable
conformance for all protocols that you are testing.
You cannot instantiate an enum case that has an associated value without actually supplying an associated value. So XCTAssertEnumCase(value, .firstCase)
cannot be achieved.
You can do XCTAssertEnumCase(testValue, .firstCase(value: 3313)
where you can pass in any Int
to the associated value of firstCase
and as long as testValue
is also firstCase
, the func will return true
, regardless of the associated values.
Alternatively, you could create separate functions for asserting each case of your enum.
extension MyEnum {
func assertFirstCase() -> Bool {
switch self {
case .firstCase:
return true
default:
return false
}
}
func assertSecondCase() -> Bool {
switch self {
case .secondCase:
return true
default:
return false
}
}
}
And then use it like this:
let value: MyEnum = .firstCase(value: 3)
value.assertFirstCase() // returns true
value.assertSecondCase() // returns false