Skip to content

Instantly share code, notes, and snippets.

@feighter09

feighter09/Weak.swift

Last active Oct 1, 2019
Embed
What would you like to do?
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