How can we use the Swift 4.2 style of capturing self in closures in functions that returns a type?
For example:
func checkEmailExists(_ email: String) -> Observable<Bool> {
return Observable.create { [weak self] observer in
guard let self = self else { return }
self.callAPI()
}
}
This generates an error Non-void function should return a value
but also it should not return false
as this will influence the outcome of the function call.
EDIT: Another example, throws 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": "[email protected]"] 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()
}
}
You have to return a disposable in any case.
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 */ }
}
}
This feels very wrong though. Your function callAPI()
should itself be returning an Observable of some sort which would make this function pointless.