Skip to content

Instantly share code, notes, and snippets.

@rehannali
Created July 8, 2020 08:24
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 rehannali/11f787f2312aa6c3c6ce840f33bd4423 to your computer and use it in GitHub Desktop.
Save rehannali/11f787f2312aa6c3c6ce840f33bd4423 to your computer and use it in GitHub Desktop.
A simple solution for [weak self] or [unowned self] dance. No need to worry about retain cycles.
struct Delegation<Input, Output> {
private(set) var callback: ((Input) -> Output?)?
mutating func delegate<Target: AnyObject>(to target: Target, _ callback: @escaping (Target, Input) -> Output) {
self.callback = { [weak target] (input) in
guard let target = target else {
return nil
}
return callback(target, input)
}
}
func call(_ input: Input) -> Output? {
return self.callback?(input)
}
var isDelegateSet: Bool {
return callback != nil
}
}
extension Delegation {
mutating func removeDelegate() {
callback = nil
}
mutating func manuallyDelegate(with callback: @escaping (Input) -> Output) {
self.callback = callback
}
mutating func strongDelegate<Target: AnyObject>(to target: Target, _ callback: @escaping (Target, Input) -> Output) {
self.callback = { input in
return callback(target, input)
}
}
}
extension Delegation where Input == Void {
func call() -> Output? {
return self.call(())
}
}
extension Delegation where Output == Void {
func call(_ input: Input) {
self.callback?(input)
}
}
extension Delegation where Input == Void, Output == Void {
func call() {
return self.call(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment