0

In ViewController.swift - I declare a lazy var game at the beginning of the class, and still get the error

Cannot use instance member 'cardButtons' within property initializer; property initializers run before 'self is' available

import UIKit

class ViewController: UIViewController {

lazy var game = Concentration(numberOfPairsOfCards: (cardButtons.count + 1) / 2)

@IBOutlet var cardButtons: [UIButton]!

var emojiChoices = ["🍆", "💩", "🍆", "💩" ]

@IBAction func touchCard(_ sender: UIButton) {
    flipCount += 1
    if let cardNumber = cardButtons.index(of: sender) {
        flipCard(withEmoji: emojiChoices[cardNumber], on: sender)
    } else {
        print("Chosen card not in cardButtons")
    }
}
}

Here is the class 'Concentration', that I am trying to create an instance of import Foundation

class Concentration {

var cards = [Card]()

init(numberOfPairsOfCards: Int) {
  for _ in 1...numberOfPairsOfCards {
    let card = Card()
    cards += [card, card]
  }
}
}
0

1 Answer 1

0

This looks like a sample project from a recent Stanford iOS course. Anyway, the syntax of your lazy var does not look correct.

change

lazy var game = Concentration(numberOfPairsOfCards: (cardButtons.count + 1)/2)

to

lazy var game : Concentration = { 
   return Concentration(numberOfPairsOfCards: (cardButtons.count + 1)/2) 
}()

However, accessing the value of another variable (cardButtons.count), although fine in your current code probably, could introduce an issue later if cardButtons has not been initialized before game is referenced.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.