Skip to content

Instantly share code, notes, and snippets.

@dorentus
Last active March 9, 2016 08:02
Show Gist options
  • Save dorentus/a244cb02cead67148519 to your computer and use it in GitHub Desktop.
Save dorentus/a244cb02cead67148519 to your computer and use it in GitHub Desktop.
import Foundation
final class Worker {
let timeout = 5
let notify: Void -> Void
init(notify: Void -> Void) {
self.notify = notify
}
func run() {
configureTimer()
dispatch_main()
}
private func configureTimer() {
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())
dispatch_source_set_timer(source, 0, UInt64(timeout) / 2 * NSEC_PER_SEC, 0)
dispatch_source_set_event_handler(source) {
self.notify()
}
dispatch_resume(source)
}
}
let worker = Worker(notify: {
print("notify!")
})
worker.run()
// original version, not working
import Foundation
final class Worker {
let timeout = 5
let notify: Void -> Void
init(notify: Void -> Void) {
self.notify = notify
}
func run() {
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())
dispatch_source_set_timer(source, 0, UInt64(timeout) / 2 * NSEC_PER_SEC, 0)
dispatch_source_set_event_handler(source) {
self.notify()
}
dispatch_resume(source)
dispatch_main()
}
}
let worker = Worker(notify: {
print("notify!")
})
worker.run()
// inlined and working
import Foundation
final class Worker {
let timeout = 5
let notify: Void -> Void
init(notify: Void -> Void) {
self.notify = notify
}
func run() {
dispatch_resume(configureTimer())
dispatch_main()
}
private func configureTimer() -> dispatch_source_t {
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())
dispatch_source_set_timer(source, 0, UInt64(timeout) / 2 * NSEC_PER_SEC, 0)
dispatch_source_set_event_handler(source) {
self.notify()
}
return source
}
}
let worker = Worker(notify: {
print("notify!")
})
worker.run()
// modified version, not working
import Foundation
final class Worker {
let timeout = 5
let notify: Void -> Void
init(notify: Void -> Void) {
self.notify = notify
}
func run() {
let source = configureTimer()
dispatch_resume(source)
dispatch_main()
}
private func configureTimer() -> dispatch_source_t {
let source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())
dispatch_source_set_timer(source, 0, UInt64(timeout) / 2 * NSEC_PER_SEC, 0)
dispatch_source_set_event_handler(source) {
self.notify()
}
return source
}
}
let worker = Worker(notify: {
print("notify!")
})
worker.run()
// another modified version, working
@dorentus
Copy link
Author

dorentus commented Mar 9, 2016

Tested using Apple Swift version 3.0-dev (LLVM a7663bb722, Clang 4ca3c7fa28, Swift 1c2f40e246) on OS X El Capitan 10.11.3 (15D21)

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