Nimble: Test enums with associated values?

Created on 13 May 2017  路  2Comments  路  Source: Quick/Nimble

How to wrap with expect(...) syntax this expression:

if case Enum.myValue(_) = variable {
    XCTAssert(true)
}

?

question / needs more details

Most helpful comment

It would be nice to be able to do it in Nimble. Using mentioned pattern, we can check for conformance to enum value, without checking its associated value. The capabilities of pattern matching like this are higher than what Equatable provides us.

enum Enum {
    case text(String)
    case number(Int)
}

let value = .number(5)

if case .text("a") = value {} // does not match
if case .text = value {} // does not match
if case .number(1) = value {} // does not match
if case .number(5) = value {} // matches
if case .number = value {} // matches

I can imagine using it in Nimble, like this:

expect(value).to(beCase(.text("a")) // does not match
expect(value).to(beCase(.text)) // does not match
expect(value).to(beCase(.number(1))) // does not match
expect(value).to(beCase(.number(5))) // matches
expect(value).to(beCase(.number)) // matches

Unfortunately, I am not sure if it can be done because of limited reflection capabilities in Swift.

All 2 comments

If you are testing equality, you can make your Enum conform to Equatable protocol and implement == operator.

Something likes:

expect(Enum.myValue) == variable

It would be nice to be able to do it in Nimble. Using mentioned pattern, we can check for conformance to enum value, without checking its associated value. The capabilities of pattern matching like this are higher than what Equatable provides us.

enum Enum {
    case text(String)
    case number(Int)
}

let value = .number(5)

if case .text("a") = value {} // does not match
if case .text = value {} // does not match
if case .number(1) = value {} // does not match
if case .number(5) = value {} // matches
if case .number = value {} // matches

I can imagine using it in Nimble, like this:

expect(value).to(beCase(.text("a")) // does not match
expect(value).to(beCase(.text)) // does not match
expect(value).to(beCase(.number(1))) // does not match
expect(value).to(beCase(.number(5))) // matches
expect(value).to(beCase(.number)) // matches

Unfortunately, I am not sure if it can be done because of limited reflection capabilities in Swift.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hamchapman picture hamchapman  路  7Comments

darrarski picture darrarski  路  4Comments

pavel-primachek picture pavel-primachek  路  3Comments

sreddy100 picture sreddy100  路  4Comments

gapl picture gapl  路  5Comments