Skip to content

Instantly share code, notes, and snippets.

@stzn
Created October 11, 2018 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stzn/5a7458d5e902a1d1be5ac83cc1a377eb to your computer and use it in GitHub Desktop.
Save stzn/5a7458d5e902a1d1be5ac83cc1a377eb to your computer and use it in GitHub Desktop.
Try To Avoid Weak-Strong Dance
func weakToStrong<T: AnyObject>(on target: T, block: ((T) -> Void)?) -> Void {
return { [weak target] in
guard let target = target else {
return
}
block?(target)
}()
}
final class LoginViewModel {
func login(loginId: String, password: String, completion: @escaping (Bool) -> Void) {
// Want to avoid this weak-strong dance
loginApiCall(loginId: loginId, password: password) { [weak self] token in
guard let self = self,
let token = token else {
completion(false)
return
}
// Something...
completion(true)
}
// use weakToStrong
loginApiCall(loginId: loginId, password: password) { token in
weakToStrong(on: self) { (self) in
guard let token = token else {
completion(false)
return
}
// Something...
completion(true)
}
}
}
func loginApiCall(loginId: String, password: String,
completion: @escaping (String?) -> Void) {
completion("token")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment