如何使用组合框架获得展开值



我对使用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)
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新