如何使用 combine 框架获取 unwrap 值

How to get unwrap value using combine framework

我对使用 Combine 框架完全陌生。 我正在使用的结构:

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)
        }
    }
}

我从服务器收到此响应:

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

我正在尝试使用组合从上面的响应中获取此值 code: Optional(["The code does not exist."]),,但我不能

我正在使用以下代码获取该值:

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

来自服务器的主要响应:

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

如何从 code 中获取值?

结果是AuthenticateResponse吧?

如果是这样的话

.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)")
}

Biclops感谢您的帮助,给了我光明。如果有人像上面那样构建这种获得你的价值的最佳方式:

.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)
            }

        }
    }
}