简体   繁体   中英

Swift enum + associated value + inline case check

I have the following swift enum for returning an async API-Response:

enum Result<U: Equatable> {
  case success(output: U)
  case failure(error: Error)
}

For simplifying my Unit test implementation i would like to check if the returned result-enum of one of my methods equals success

I know that i can unwrap the result-enum by using the following statement

if case Result.success(let configuration) = result {
    // use unwrapped configuration object
}

What i would like to archive is using a single line statement to check if the result is success when checking with expect

expect(case Result.success(let configuration) = result).to(beTrue()) <-- not compiling

If you goal is to check only success/failure (not the details of success or failure cases) you can extend you enum with read-only variables isSuccess and isFailure :

enum Result<U: Equatable> {

    case success(output: U)
    case failure(error: Error)

    var isSuccess: Bool {
        switch self {
        case .success:
            return true
        default:
            return false
        }
    }
    var isFailure: Bool {
        switch self {
        case .failure:
            return true
        default:
            return false
        }
    }
}

And expect the result to be a success:

expect(result.isSuccess)

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