Last active
October 1, 2019 14:23
-
-
Save feighter09/88e4c5ffd83e6233f8db8367b43fcf14 to your computer and use it in GitHub Desktop.
A helper to weakly capture an object in a block
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 weak<Object: AnyObject>(_ object: Object, block: @escaping (Object) -> Void) -> () -> Void { | |
return { [weak object] in | |
guard let object = object else { return } | |
block(object) | |
} | |
} | |
func weak<Object: AnyObject, Input>(_ object: Object, block: @escaping (Object, Input) -> Void) -> (Input) -> Void { | |
return { [weak object] in | |
guard let object = object else { return } | |
block(object, $0) | |
} | |
} | |
func weak<Object: AnyObject, Input, Output>(_ object: Object, block: @escaping (Object, Input) -> Output) -> (Input) -> Output? { | |
return { [weak object] in | |
guard let object = object else { return nil } | |
return block(object, $0) | |
} | |
} | |
// Uses: | |
let blockBefore: () -> Void = { [weak self[ in | |
guard let self = self else { return } | |
self.doSomething() | |
} | |
let blockAfter: () -> Void = weak(self) { _self in _self.doSomething() } | |
let blockBefore: (Int) -> Void = { [weak self] number in | |
guard let self = self else { return } | |
self.update(number) | |
} | |
let blockAfter: (Int) -> Void = weak(self) { _self, number in _self.update(number) } | |
let blockBefore: (Int) -> String? = { [weak self] number in | |
guard let self = self else { return nil } | |
return self.string(from: number) | |
} | |
let blockAfter: (Int) -> String? = weak(self) { _self, number in _self.string(from: number) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment