Skip to content

Instantly share code, notes, and snippets.

@feighter09
Last active October 1, 2019 14:23
Show Gist options
  • Save feighter09/88e4c5ffd83e6233f8db8367b43fcf14 to your computer and use it in GitHub Desktop.
Save feighter09/88e4c5ffd83e6233f8db8367b43fcf14 to your computer and use it in GitHub Desktop.
A helper to weakly capture an object in a block
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