0

I am making a jumping game using Swift 4 and I am running into an error with the following code:

func addRandomForegroundOverlay() {
    let overlaySprite: SKSpriteNode!
    let platformPercentage = 60
    if Int.random(min: 1, max: 100) <= platformPercentage {
        overlaySprite = platform5Across
    } else {
        overlaySprite = coinArrow
    }
    createForegroundOverlay(overlaySprite, flipX: false)
}

The error comes on line 4 and says: Type Int has no member random.

2 Answers2

1

The Int type doesn't provide a random() method.

Since you are making a game, using GameplayKit.GKRandom might be a good fit. Try this instead:

import GameplayKit
...
let randomizer = GKRandomSource.sharedRandom()
let randomInt = 1 + randomizer.nextInt(upperBound: 100) // 1...100

Or, better yet, implement the missing method yourself ;)

extension Int {
    static func random(min: Int, max: Int) -> Int {
        precondition(min <= max)
        let randomizer = GKRandomSource.sharedRandom()
        return min + randomizer.nextInt(upperBound: max - min + 1)
    }
}

usage:

let randomInt = Int.random(min: 1, max: 100)
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
1

Simplest way would be to use Int(arc4random_uniform(100))

Evan
  • 750
  • 7
  • 13