Reputation:
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
.
Upvotes: 1
Views: 4902
Reputation: 19339
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)
Upvotes: 1