Created
September 26, 2017 16:45
-
-
Save soxjke/dd92be6fbe322b95cfd119da4bb203f6 to your computer and use it in GitHub Desktop.
NoRetainCycle
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
//: Playground - noun: a place where people can play | |
import Foundation | |
prefix operator ~ | |
prefix func ~<Entity, Parameters>(_ param: ((Entity) -> (Parameters) -> (), Entity)) -> WeakCallback<Parameters> | |
where Entity: AnyObject | |
{ | |
return WeakCallback.weakifyFunction(param.0, object: param.1) | |
} | |
class WeakCallback<Parameters> { | |
private let innerCallback: (Parameters) -> () | |
init(_ f: @escaping (Parameters) -> ()) { | |
innerCallback = f | |
} | |
func call(_ parameters: Parameters) { | |
innerCallback(parameters) | |
} | |
static func weakifyFunction<Entity>(_ f: @escaping (Entity) -> (Parameters) -> (), object: Entity) -> WeakCallback<Parameters> | |
where Entity: AnyObject | |
{ | |
return WeakCallback({ [weak object] (parameters) in | |
object.map { f($0)(parameters) } | |
}) | |
} | |
} | |
class Base { | |
deinit { | |
print("\(String(describing: self)) deinitialized") | |
} | |
} | |
class Processor: Base { | |
typealias Callback = (Processor) -> () | |
var callback: WeakCallback<Processor>? | |
func process() { | |
// ... do something | |
self.callback?.call(self) | |
} | |
} | |
class Data: Base { | |
let processor = Processor() | |
override init() { | |
super.init() | |
processor.callback = (~)((Data.onProcessingFinished, self)) | |
} | |
func process() { | |
self.processor.process() | |
} | |
func onProcessingFinished(processor: Processor) { | |
print("procesing complete") | |
} | |
} | |
var data: Data? = Data() | |
data?.process() | |
data = nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment