3

I am making a Concentration game by following along with lectures online from the stanford course, and I am getting an error for one part of my code. I am getting the error "Instance member 'cardButtons' cannot be used on type 'ViewController'", but the code seems to be working for the instructor. Could someone help me fix this? Here is part of the code. Error occurs in the 4th line

import UIKit

class ViewController: UIViewController {

@IBOutlet var cardButtons: [UIButton]!

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

var flipCount = 0 {
    didSet {
        flipCountLabel.text = "Flips: \(flipCount)"
    }
}

@IBOutlet weak var flipCountLabel: UILabel!


@IBAction func touchCard(sender: UIButton) {
    flipCount += 1
    if let cardNumber = cardButtons.indexOf(sender) {
        game.chooseCard(at: cardNumber)
        updateViewFromModel()
    } else {
        print("chosen card was not in array cardButtons")
    }

}

func updateViewFromModel() {
    for index in cardButtons.indices {
        let button = cardButtons[index]
        let card = game.cards[index]
        if card.isFaceUp {
            button.setTitle(emoji, forState: UIControlState.Normal)
            button.backgroundColor = UIColor.whiteColor()
        } else {
            button.setTitle("", forState: UIControlState.Normal)
            button.backgroundColor = card.isMatched ? UIColor.clearColor() : UIColor.orangeColor()
        }

    }
}

    var emojiChoices = ["", "", "", "", "", "", "", "", "", ""]

func emoji(for card:Card) -> String {
    return "?"
}

}

2 Answers2

5

Change this line

 var game : Concentration {

    return  Concentration(numberOfPairsOfCards: self.cardButtons.count / 2)

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
2

You are trying to use an instance (cardButtons) of ViewController, which is not initialised. You can use instances of ViewController, once you view controller is loaded, i mean, inside viewDidLoad()

Look at life cycle of UIViewController, to understand issue.

Try this and see:

class ViewController: UIViewController {

    @IBOutlet var cardButtons: [UIButton]!

    var game: Concentration?

    //or 
    //var game: Concentration!

    //or 
    //var game = Concentration()

    //or
    /*
    var game: Concentration {
       return Concentration(numberOfPairsOfCards: cardButtons.count / 2) 
    }
    */
    override func viewDidLoad() {
        super.viewDidLoad()
        game = Concentration(numberOfPairsOfCards: cardButtons.count / 2)
    }




}
Krunal
  • 77,632
  • 48
  • 245
  • 261