Created
October 11, 2018 00:15
-
-
Save stzn/5a7458d5e902a1d1be5ac83cc1a377eb to your computer and use it in GitHub Desktop.
Try To Avoid Weak-Strong Dance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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