Betkowski
Betkowski

Reputation: 491

Swift - Select Random Function

I think this could be useful.

I've got a bunch of functions, in an array. For example, let's say its:

var randomFunction = [addEnemyFromCornersTogether(), addEnemyFromCornersWait()]
var randomFunctionDelay = NSTimeInterval(5.0)

I want to choose them randomly with delay set in a variable. No idea how to do that. Any tips?

Upvotes: 0

Views: 159

Answers (1)

Krys Jurgowski
Krys Jurgowski

Reputation: 2911

func fireEvent() {
    var randomFunction = [addEnemyFromCornersTogether(), addEnemyFromCornersWait()]
    let choice = Int(arc4random_uniform(UInt32(randomFunction.count)))
    var choiceFunction: () = randomFunction[choice]
    let delay = 5.0 * Double(NSEC_PER_SEC)
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue(), {
        choiceFunction
        fireEvent()
    })
}

Upvotes: 1

Related Questions