Access enum associated value as optional

前端 未结 3 878
死守一世寂寞
死守一世寂寞 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 {
      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.success(1)
    let resultFailure = Result.failure("Error")
    
    if let error = resultFailure.failureValue {
      // do something
      print(error)
    }
    

提交回复
热议问题