0

I want to get a random value between 5 defined points, without getting the same result twice.

Here is a good explanation of how to avoid the same result twice: How to generate a random number in Swift without repeating the previous random number?

However, in my Code it doesn't work as it still is completely random, and I can't see why.

 func addWall(){

    let positions = [
        CGPoint(x: -120,y: -70),
        CGPoint(x: -50,y: -70),
        CGPoint(x: 10,y: -70),
        CGPoint(x: 70,y: -70),
        CGPoint(x: 120, y: -70),
    ]

    var previousPosition : Int?

    func randomPosition() -> Int {
        var randomPosition = Int(arc4random_uniform(UInt32(positions.count)))
        while previousPosition == randomPosition {
            randomPosition = Int(arc4random_uniform(UInt32(positions.count)))
        }
        previousPosition = randomPosition
        return randomPosition
    }

    Wall.position = positions[randomPosition()]
}
Community
  • 1
  • 1

1 Answers1

0

Your property

var previousPosition : Int?

is local to the addWall() method, and therefore initialized to nil each time the method is called. If you make it a property of the surrounding class instead:

class YourClass {

    var previousPosition : Int?

    func addWall() { ... }

    // ...
}

then it is initialized to nil only when an instance of the class is created.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382