Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

How to get unwrap value using combine framework

I am totally new at using the Combine framework. The struct I am using:

enum AuthenticateResponse: Decodable, Hashable {
    struct Success: Decodable, Hashable {
        let url, id, firstName, lastName: String
        let email, phone: String
    }

    struct Failure: Decodable, Hashable {
        struct Errors: Decodable, Hashable {
            let code: [String]?
            let username: [String]?
            let password: [String]?
        }
        let message: String
        let errors: Errors
    }

    case success(Success)
    case failure(Failure)
    init(from decoder: Decoder) throws {
        do {
            let success = try Success(from: decoder)
            self = .success(success)
        } catch {
            let failure = try Failure(from: decoder)
            self = .failure(failure)
        }
    }
}

I am getting this response from server:

failure(demo.AuthenticateResponse.Failure(
    message: "Invalid data..", 
    errors: demo.AuthenticateResponse.Failure.Errors(
        code: Optional(["The code does not exist."]), 
        username: nil, 
        password: nil)
    )
)

I am trying to get this value code: Optional(["The code does not exist."]), from above response using combine but I couldn’t

I am using below code to get that value:

func syncOnlineData() {
    print("I am here")
    viewModel.authenticateResponse
        .sink { result in
            print("result: \(result)")
        } receiveValue: { res in
            print("value: \(String(describing: res))")
        }
} 

main response from server:

["errors": {
    code =     (
        "The code does not exist."
    );
}, "message": Invalid data.]

How I will get the value from code ?

Upvotes: 0

Views: 360

Answers (2)

Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

Biclops thanks for your help and giving me the light. If someone structure like above one this kinda best way to get your value:

.sink { result in
    switch result {
    case .none:
        print("--")
    case .some(let jsonValue):
        switch jsonValue {
        case .success(let success):
            self.verificationMessageLabel.isHidden = true
            self.continueButton.isEnabled = true
            print("success: \(success)")
        case .failure(let fail):
            guard let errorMsg = fail.errors.code else { return }
            errorMsg.forEach { errString in
                print(errString)
            }

        }
    }
}

Upvotes: 0

Yogurt
Yogurt

Reputation: 3045

The result is the AuthenticateResponse right?

If that's the case

.sink { result in 
    guard case .failure(let failure) = result else { return }

    // here is the code for each error
    print("do something for code: \(failure.errors.code)")
}

Upvotes: 1

Related Questions