Skip to content

Instantly share code, notes, and snippets.

@tarunon
Created October 20, 2015 09:34
Show Gist options
  • Save tarunon/fb0889a752d6702c3165 to your computer and use it in GitHub Desktop.
Save tarunon/fb0889a752d6702c3165 to your computer and use it in GitHub Desktop.
Takahashi-meijin can push a button 16 times per 1 second.
final class UTContainer<T> {
var value: T {
didSet {
if self.fired {
self.fired = false
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: NSBlockOperation { [weak self] in
guard let strongSelf = self else {
return
}
strongSelf.fired = true
strongSelf.handler(strongSelf.value)
}, selector: "main", userInfo: nil, repeats: false)
} else {
self.timer?.fireDate = NSDate(timeIntervalSinceNow: 1.0)
}
}
}
private var timer: NSTimer?
private var handler: T -> ()
private var fired = true
init(_ value: T, handler: T -> ()) {
self.value = value
self.handler = handler
}
}
@tarunon
Copy link
Author

tarunon commented Oct 20, 2015

var f = UTContainer(0) { i in
    print(i)
}
f.value = 1 // nop
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.5))
f.value = 2 // nop
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.5))
f.value = 3 // print
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 1.2))
f.value = 4 // nop
NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.5))
f.value = 5 // print

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment