Home > front end >  Swift access enum param
Swift access enum param

Time:03-03

I have this function:

@objc(syncUser:rejecter:)
  func syncUser(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
    self.cancelableSyncUser = MyService.shared?.syncingUser()
      .sink(receiveCompletion: {
        switch $0 {
        case .failure(let error):
          print("PRINT \(error)")
          reject(error.localizedDescription, error.localizedDescription, error);
        case .finished:
          
        }
      }, receiveValue: {
        resolve($0);
      })
  }

I get an error object that contains some information that I want to use, but I cannot access its properties (code and message).

If I print the error object, I get this:

PRINT syncUser(Optional(mydomain.OpenpathErrorData(err: mydomain.OpenpathErrorData.Err(message: "Error message", code: "X"))), nil)

As we can see, it contains code and message.

OpenpathErrorData is an enum defined in another class:

  enum OpenpathError: Error {
    case syncUser(OpenpathErrorData?, Error?)
  }
struct OpenpathErrorData: Codable {
  struct Err: Codable {
    var message:String
    var code:String
  }
  var err: Err
}

The problem is that I cannot access those properties. I can only access error.localizedDescription.

I've tried everything but either I cannot access it or I don't know the right syntax.

Any ideas? I know it's hard to understand without seeing the whole code but if it's about the syntax maybe someone can give me a hint.

Thanks a lot in advance.

CodePudding user response:

You can use if case ... to access the content of the error structure.

if case let OpenpathError.syncUser(errorData, otherError) = error 

With this we check if error is of the case .synchUser and at the same time we also assign the associated values of the enum case to the two (optional) variables errorData and otherError that you can then use in your code.

if case let OpenpathError.syncUser(errorData, otherError) = error {

    if let errorData = errorData {
        print(errorData.err.message, errorData.err.code)
    }

    if let otherError = otherError {
        print(otherError)
    }
}
  • Related