How can I access an enum value for a specific case without having to implement an enum function for each case?
I\'m thinking something like this:
enum Re
Add two computed properties for success case and failure case respectively.
enum Result<S, F> {
case success(S)
case failure(F)
var successValue: S? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
var failureValue: F? {
switch self {
case .failure(let value):
return value
case .success:
return nil
}
}
}
let resultSuccess = Result<Int, String>.success(1)
let resultFailure = Result<Int, String>.failure("Error")
if let error = resultFailure.failureValue {
// do something
print(error)
}
I'm afraid this is the most you can get:
let error: String?
if case .failure(let e) = resultFailure {error = e}
This technique from the question "Accessing an Enumeration association value in Swift" will do it:
enum Result<S, F> {
case success(S)
case failure(F)
}
let resultFailure = Result<Int, String>.failure("Error")
var error: String?
if case let Result.failure(value) = resultFailure {
error = value
}
print(error) // Optional("Error")
This will also work in place of the "if case let =" construct:
switch resultFailure {
case let Result.failure(value): error = value
default : error = nil
}
Here you go, 1 line and uses let
:
let error: String? = { if case let .failure(value) = resultFailure { return value }; return nil }()