1

I am making a rhythm app, but I can't seem to randomize the circles. Here is my code:

var alternator = 0
var fallTimer:NSTimer?
var flag:Bool = true

let circleIndexes = (0..<5).map { return NSNumber(integer: $0) }

let randomIndexes = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(circleIndexes) as! [Int]

func fallCircleWrapper() {

    if (flag == true) {
        self.alternator += 1
    } else {
        self.alternator -= 1
    }

    if (self.alternator == 0) {
        flag = true
    } else if (self.alternator == 5) {
        flag = false
    }

    self.hitAreaArray[randomIndexes[self.alternator]].emitNote(self.texture!)

}

The problem is with this line:

let randomIndexes = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(circleIndexes) as! [Int]

which gives the error "Instance member 'circleIndexes' cannot be used on type 'GameScene'". How should I go about fixing this?

Dima
  • 23,484
  • 6
  • 56
  • 83
shadokyr
  • 65
  • 4
  • 1
    Are that properties of a *class?* In that case it would be a duplicate of [How to initialize properties that depend on each other](https://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other). – Martin R May 24 '17 at 20:18
  • 1
    Why are you using Swift 2 instead of 3 for a new app? – TheValyreanGroup May 24 '17 at 22:47

1 Answers1

1

Consider this example that reproduces your error on a simpler scale:

func agePlusOne(_ num: Int) -> Int { return num + 1 }

class Cat {

  var age = 5
  var addedAge = agePlusOne(age) // ERROR!
}

You're trying to use a property /before/ it has been initialized... that is, before init() has finished, thus giving you a self to work with.

A way around this is to use lazy properties... lazy properties are initialized only when first called by an object.. that is, they are properly initialized only after there is a self available.

private(set) lazy var randomIndices: [Int] = {
GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(self.circleIndexes) as! [Int]
}()

computed and static properties are also lazy by default, without needing to use the keyword. Unfortunately, you cannot use lazy let, so the private(set) was added to give you more immutability, but not total.

PS, this is Swift3 so you may need to convert it to Swift2.

Fluidity
  • 3,985
  • 1
  • 13
  • 34