在Swift 4.2保护函数中的闭包中捕获Self时出现“非空函数应返回值”

时间:2018-12-03 14:48:42

标签: swift rx-swift self

我们如何使用Swift 4.2样式在返回类型的函数的闭包中捕获自身?

例如:

func checkEmailExists(_ email: String) -> Observable<Bool> {
    return Observable.create { [weak self] observer in
        guard let self = self else { return }
        self.callAPI()
    }
}

这会产生错误Non-void function should return a value,但也不应return false,因为这会影响函数调用的结果。

编辑:另一个例子,抛出Non-void function should return a value

func loginWithCredentials() -> Observable<User> {
    return Observable.create { [weak self] observer in
        guard let self = self else { return }

        let decoder = JSONDecoder()
        let json = ["id": 1, "name": "John Doe", "email": "john@doe.com"] as [String: Any]

        do {
            let user = try decoder.decode(User.self, from: json.jsonData()!)
            observer.onNext(user) // Simulation of successful user authentication.
        } catch {
            print("error")
        }

        return Disposables.create()
    }
}

2 个答案:

答案 0 :(得分:1)

在任何情况下,您都必须退回一次性用品。

TASK [node : Install node and set version] *************************************************************************************
    fatal: [51.15.128.164]: FAILED! => {"changed": true, "cmd": "nvm install 8.11.3", "delta": "0:00:00.005883", "end": "2018-12-03 15:05:10.394433", "msg": "non-zero return code", "rc": 127, "start": "2018-12-03 15:05:10.388550", "stderr": "/bin/sh: 1: nvm: not found", "stderr_lines": ["/bin/sh: 1: nvm: not found"], "stdout": "", "stdout_lines": []}
        to retry, use: --limit .../.../ansible/stater-debian/playbook.retry

但是,这感觉非常错误。您的函数func checkEmailExists(_ email: String) -> Observable<Bool> { return Observable.create { [weak self] observer in guard let self = self else { return Disposables.create() } // and so on... return Disposables.create { /* cancelation code */ } } } 应该本身返回某种使该函数毫无意义的Observable。

答案 1 :(得分:-3)

尝试将返回类型设置为可选,如果没有 self ,则返回nil

OR

您可以通过使用带有guard符号的方法来调用?语句,例如:

self?.callAPI()