Access enum associated value as optional

前端 未结 3 879
死守一世寂寞
死守一世寂寞 2021-01-26 03:01

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         


        
相关标签:
3条回答
  • 2021-01-26 03:37

    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)
    }
    
    0 讨论(0)
  • 2021-01-26 03:43

    I'm afraid this is the most you can get:

        let error: String?
        if case .failure(let e) = resultFailure {error = e}
    
    0 讨论(0)
  • 2021-01-26 03:50

    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 }()
    
    0 讨论(0)
提交回复
热议问题