1

I'm stuck at a variable declaration in Swift 3. My code looks like this:

Beginning of code

// Letter Buttons
@IBOutlet weak var LetterOneButton: UIButton!
@IBOutlet weak var LetterTwoButton: UIButton!
@IBOutlet weak var LetterThreeButton: UIButton!
@IBOutlet weak var LetterFourButton: UIButton!
@IBOutlet weak var LetterFiveButton: UIButton!

// Word Fields
@IBOutlet weak var WordLetterOne: UILabel!
@IBOutlet weak var WordLetterTwo: UILabel!
@IBOutlet weak var WordLetterThree: UILabel!
@IBOutlet weak var WordLetterFour: UILabel!
@IBOutlet weak var WordLetterFive: UILabel!

// Counter
@IBOutlet weak var CounterLabel: UILabel!

// Skip Button
@IBOutlet weak var SkipButtonLabel: UIButton!

// Define Variables
var index: Int = 0

The error appears in the following line:

var labels: [UILabel] = [WordLetterOne, WordLetterTwo, WordLetterThree, WordLetterFour, WordLetterFive]

Error message is "Cannot use instance member 'WordLetterOne' within property initializer; property initializers run before 'self' is available". Afterwards, another string is declared without any problems.

var letters: [String] = ["A", "B", "C", "D", "E"] 

End of code

And help is highly appreciated!

Edit:

self.lazy var labels: [UILabel] = [WordLetterOne, WordLetterTwo, WordLetterThree, WordLetterFour, WordLetterFive]

is giving the errors "Consecutive declarations on a line must be separated by ';'" and "Instance member 'WordLetterOne' cannot be used on type 'ViewController'"

j___.___j
  • 286
  • 1
  • 3
  • 20

1 Answers1

0

Like it says: when the runtime builds the array initalizer, the properties you're trying to put in the array are not defined yet (because self is not ready yet).

Try to make the properties static (depends on your actual situation). Or -- initialize the labels array in the init method.

The definition of letters is ok because "A", "B", etc are constants.

noamtm
  • 12,435
  • 15
  • 71
  • 107
  • Thank you! Can you give me an example of how exactly that would look in the above mentioned case? Thanks in advance for your effort! – j___.___j Sep 25 '16 at 18:42
  • Try @vacawama's suggestion in the comment (lazy) -- sounds like a very clean solution (haven't tested it). – noamtm Sep 25 '16 at 19:40