Skip to content

Instantly share code, notes, and snippets.

@lacyrhoades
Last active October 19, 2017 07:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lacyrhoades/f917b971e97fdecf9607669501ef6512 to your computer and use it in GitHub Desktop.
Save lacyrhoades/f917b971e97fdecf9607669501ef6512 to your computer and use it in GitHub Desktop.
func debug() {
let manager = ThingManager()
let thing1 = Thing(name: "thing1")
manager.addThing(thing1)
manager.sawSomeThing(named: thing1.name)
print("Manager has this many things: ", manager.things.count)
Timer.scheduledTimer(withTimeInterval: 10.0, repeats: false, block: { (timer) in
// By now, the manager should have forgotten about the thing
print("Manager has this many things: ", manager.things.count)
})
}
struct Thing {
var name: String
}
class ThingManager {
var things: [String: Thing] = [:]
fileprivate var thingWatchingQueue = DispatchQueue.global()
fileprivate var thingWatchingTimers: [String: Timer] = [:]
func addThing(_ thing: Thing) {
self.things[thing.name] = thing
}
func sawSomeThing(named name: String) {
self.thingWatchingQueue.async {
// re-up the timer so we don't forget about that thing
if let timer = self.thingWatchingTimers[name] {
timer.invalidate()
}
self.thingWatchingTimers[name] = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false, block: { (timer) in
self.removeThing(named: name)
})
}
}
func removeThing(named name: String) {
self.things.removeValue(forKey: name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment