简体   繁体   中英

Extracting raw value of a Error enum case

I have created a Result enum to propagate the result of a REST API call.

enum Result {
    case success([AnyObject])
    case failure(APIError)
}

I also have a Error enum to handler errors

enum APIError: Error {
    case requestFailed(String)
    case invalidData(String)
    case invalidQuery(String)
    case invalidURL(String)
}

I send the error in a completion closure like

completion(.failure(.invalidURL("Invalid URL")))

How can I access this string in a if case scenario?

I am trying to do something like

if case .failure(let res) = result /*, case res.invalidQuery(let invalid) */ {
    print(res)
}

How can I achieve this?

If what you're trying to do is having two cases on the same line, you can do it like so:

if case .failure(let error) = result, case .invalidQuery(let message) = error {
    print(message)
}

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