Last active
April 20, 2016 16:36
-
-
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/
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 | |
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to using a calculated property for the multiplier rather than a static, and the newer method of setting a playground to run indefinitely.