functionswiftreturn-typearc4random

Swift Random Function


I am making a game that generates random obstacles for the player, so i want to have a function that returns a random function that generates the obstacle.

 func createObstacle() {

        var obstacles = [obstacle1(), obstacle2(), obstacle3()]

        var randomObstacle = Int(arc4random_uniform(UInt32(obstacles.count)))

        var obstacle = obstacles[randomObstacle]
    }

The problem is i don't really know how to make my function return another function.


Solution

  • Assuming I'm understanding your question correctly, you want this:

     func createObstacle() -> () -> () {
    
        var obstacles = [obstacle1, obstacle2, obstacle3]
    
        var randomObstacle = Int(arc4random_uniform(UInt32(obstacles.count)))
    
        return obstacles[randomObstacle]
    }
    

    Check out the documentation section about functions: https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-XID_243