首页 > 解决方案 > 结合:如何从保护前提条件中提前退出错误

问题描述

我想创建一个方法authenticate,使用组合,允许用户使用我的 API 登录。

我现在正在尝试添加一个先决条件,这样如果提供的用户名为空,我的方法就不会触及网络。我想在这一点上提前存在,向订阅者提供一个错误。

请在下面找到我的代码片段。我如何从第 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 { $0.data }
            .decode(type: AuthenticationResult.self, decoder: JSONDecoder())
            .map { $0.user }
            .receive(on: RunLoop.main)
            .eraseToAnyPublisher()
    }

标签: iosswiftcombine

解决方案


您可以使用Fail,这是一种Publisher

return Fail(error: MyError.missingUsername).eraseToAnyPublisher()

推荐阅读