shadokyr
shadokyr

Reputation: 65

Swift 2 Instance member 'circleIndexes' cannot be used on type 'GameScene'

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?

Upvotes: 1

Views: 49

Answers (1)

Fluidity
Fluidity

Reputation: 3995

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.

Upvotes: 1

Related Questions