Skip to content

Instantly share code, notes, and snippets.

@Abizern
Last active April 20, 2016 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Abizern/c030bd9674b2ad881b44 to your computer and use it in GitHub Desktop.
Save Abizern/c030bd9674b2ad881b44 to your computer and use it in GitHub Desktop.
An example of overloaded functions in Swift. - More explanation at http://abizern.org/2015/10/11/swift-function-overloading-by-return-type/
//: Playground - noun: a place where people can play
import Foundation
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
// Extend NSTimeInterval to provide the conversion functions.
extension NSTimeInterval {
var nSecMultiplier: Double {
return Double(NSEC_PER_SEC)
}
public func nSecs() -> Int64 {
return Int64(self * nSecMultiplier)
}
public func nSecs() -> UInt64 {
return UInt64(self * nSecMultiplier)
}
public func dispatchTime() -> dispatch_time_t {
// Since the last parameter takes an Int64, the version that returns an Int64 is used.
return dispatch_time(DISPATCH_TIME_NOW, self.nSecs())
}
}
// Define a simple function for getting a timer dispatch source.
func repeatingTimerWithInterval(interval: NSTimeInterval, leeway: NSTimeInterval, action: dispatch_block_t) -> dispatch_source_t {
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())
guard timer != nil else { fatalError() }
dispatch_source_set_event_handler(timer, action)
// This function takes the UInt64 for the last two parameters
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, interval.nSecs(), leeway.nSecs())
dispatch_resume(timer)
return timer
}
// Create the timer
let timer = repeatingTimerWithInterval(1, leeway: 0.1) { () -> Void in
print("Hello!")
}
// Turn off the timer after a few seconds
dispatch_after(3.0.dispatchTime(), dispatch_get_main_queue()) { () -> Void in
dispatch_source_cancel(timer)
}
@Abizern
Copy link
Author

Abizern commented Apr 20, 2016

Updated to using a calculated property for the multiplier rather than a static, and the newer method of setting a playground to run indefinitely.

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