Created
July 27, 2017 21:15
-
-
Save wildthink/51eafa5b43f3cc9bfe7dc5b1e392a496 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
// Use of the protocol allows us to hold collections of ActionTrampolices of any type T | |
protocol Action { | |
func performAction() -> Bool | |
} | |
class ActionTrampoline<T: AnyObject>: NSObject, Action | |
{ | |
weak var target: T? | |
var action: (T) -> Void | |
init(target: T?, action: @escaping (T) -> Void) { | |
self.target = target | |
self.action = action | |
} | |
@objc func performAction() -> Bool { | |
guard let target = target else { return false } | |
action(target) | |
return true | |
} | |
} | |
class Target { | |
var actions = [Action]() | |
func addObserver<T: AnyObject> (_ target: T?, action: @escaping (T) -> Void) { | |
let action = ActionTrampoline (target: target, action: action) | |
actions.append(action) | |
} | |
func broadcast() { | |
for action in actions { | |
action.performAction() | |
} | |
} | |
} | |
class Foo: NSObject { | |
func print (_ msg: String) { | |
Swift.print (msg) | |
} | |
} | |
let target = Target() | |
var foo: Foo? = Foo() | |
//target.addObserver(Foo) { f in | |
// f.print ("got it") | |
//} | |
let action = ActionTrampoline(target: foo) { (f) in | |
f.print("Got it") | |
Swift.print ("Hello") | |
} | |
action.performAction() | |
target.addObserver(foo) { (f) in | |
f.print("Got another \(type (of:f))") | |
Swift.print ("Hello") | |
} | |
let nsstr: NSString = "George" | |
target.addObserver(nsstr) { | |
Swift.print ("String it \($0.lowercased)") | |
} | |
//foo = nil | |
target.broadcast() | |
//Swift.print ("Hello") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment