Reputation: 1
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]
}
}
}
Upvotes: 0
Views: 122
Reputation: 1341
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.
Upvotes: 0