Last active
May 4, 2016 17:33
-
-
Save stonetip/19256e2692708cc2759c73e62b8541d2 to your computer and use it in GitHub Desktop.
iOS Swift playground implementing a delayed function multiple times
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
import Foundation | |
import XCPlayground | |
// Allows execution to be indefinite, giving delays or callbacks time to play | |
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true | |
// Delay function | |
func delayer(duration: Double, closure:()->()){ | |
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(duration * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure) | |
} | |
func doSomething(counter: Int, max: Int){ | |
print("executing \(counter)") | |
if(counter == max){ | |
// Probably don't need this, but why not stop execution when all is said and done? | |
XCPlaygroundPage.currentPage.finishExecution() | |
} | |
} | |
// Run it once just to see if things are working | |
doSomething(-1, max: 9999) | |
// Loop to run delay multiple times | |
for index in 0...4{ | |
// For fun, we'll make our delay exponential...as might be done in an exponential backoff call | |
let duration = Double(pow(Double(index), 1.414)) | |
// Next two lines show how bat-shit crazy and incomplete Swift is...left in for posterior posterity | |
let counterStr = String(duration) | |
let subbed = counterStr.substringWithRange(Range<String.Index>(counterStr.startIndex..<counterStr.startIndex.advancedBy(3))) | |
// This is much better....and also rounds for us! | |
let substr = String(format: "%.1f", duration) | |
// Prints part of a list showing us what delays to expect | |
print("\(index), delay: \(substr)") | |
// Delay calling the function | |
delayer(duration){ | |
doSomething(index, max: 4) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment