结合:如何从警卫前提条件中提前退出并出错
Combine: how to early exit with error from a guard precondition
我想创建一个方法 authenticate
,使用 Combine,允许用户使用我的 API 登录。
我正在尝试添加一个先决条件,这样如果提供的用户名是空的,我的方法就不会触及网络。我想在此时早点存在,向订阅者返回一个错误。
请在下面找到我的代码片段。我怎么会 return 第 4 行出现早期的错误?
func authenticate(username: String, password: String) -> AnyPublisher<User, Error> {
guard !username.isEmpty else {
// How to return an error to the subscribers from here?????
return
}
let parameters: [String: Any] = [
"username": username,
"password": password
]
var request = URLRequest(endpoint: Endpoint.login)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
return URLSession.shared.dataTaskPublisher(for: request)
.map { [=10=].data }
.decode(type: AuthenticationResult.self, decoder: JSONDecoder())
.map { [=10=].user }
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
您可以使用 Fail
,它是 Publisher
:
的一种类型
return Fail(error: MyError.missingUsername).eraseToAnyPublisher()
我想创建一个方法 authenticate
,使用 Combine,允许用户使用我的 API 登录。
我正在尝试添加一个先决条件,这样如果提供的用户名是空的,我的方法就不会触及网络。我想在此时早点存在,向订阅者返回一个错误。
请在下面找到我的代码片段。我怎么会 return 第 4 行出现早期的错误?
func authenticate(username: String, password: String) -> AnyPublisher<User, Error> {
guard !username.isEmpty else {
// How to return an error to the subscribers from here?????
return
}
let parameters: [String: Any] = [
"username": username,
"password": password
]
var request = URLRequest(endpoint: Endpoint.login)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
return URLSession.shared.dataTaskPublisher(for: request)
.map { [=10=].data }
.decode(type: AuthenticationResult.self, decoder: JSONDecoder())
.map { [=10=].user }
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
您可以使用 Fail
,它是 Publisher
:
return Fail(error: MyError.missingUsername).eraseToAnyPublisher()