Swift Random Function

1.2k views Asked by At

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.

4

There are 4 answers

2
bjtitus On BEST ANSWER

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

0
Nate Cook On

When you create your array, don't execute the function, simply use their names:

func obstacle1() -> Int {
    return 1
}

func obstacle2() -> Int {
    return 2
}

func obstacle3() -> Int {
    return 3
}

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

    return obstacles[randomObstacle]
}

The return type of the function in this example is () -> Int -- I used Int to show you could have a return value from your function. () -> () would be a function without a return value.

You can alternately create a type alias for the type of your obstacle function, and return that:

typealias ObstacleFunction = () -> Int

func getObstacle() -> ObstacleFunction {
    // ..
}
0
yefimovv On
func createObstacle() {

let randomNumber = Int.random(in: 0...2)

if randomNumber == 0 {
    obstacle1()
} else if randomNumber == 1 {
    obstacle2()
} else if randomNumber == 2 {
    obstacle3()
}
}
0
Bigfoot11 On

You can use this code for your random obstacle.

func createObstacle() -> () -> () {

var obstacles = [obstacle1, obstacle2, obstacle3]

var randomObstacle = obstacle\(arc4random_uniform(3) + 1)

return obstacles[randomObstacle]
}

Hope this will help you.