0

I am following the standford ios class for Fall 2017. As the professor goes through the demo, I follow by inputting and running like he does. He shows how using lazy with a var allows one to use the UIButton count for variable initialization. When I add the lazy keyword, the error doesn't go away. Thinking it was maybe an xcode update related problem, I downloaded someone else's version of the project and that project doesn't have the issue. The code is below, any thoughts? :/

class ViewController: UIViewController {

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


//Could have had var flipCount: Int = 0
//But it is inferred
var flipCount = 0 {
    didSet {
        flipCountLabel.text = "Flips: \(flipCount)"
    }
}

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

@IBOutlet var cardButtons: [UIButton]!


@IBOutlet weak var flipCountLabel: UILabel!

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


func flipCard(withEmoji emoji: String, on button: UIButton) {
    if button.currentTitle == emoji {
        button.setTitle("", for: UIControlState.normal)
        button.backgroundColor = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)
    } else {
        button.setTitle(emoji, for: UIControlState.normal)
        button.backgroundColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 1)
    }
}

}

owlaf
  • 1
  • 4

1 Answers1

0

To initialize a lazy property which depends on the value of another property you have to use the closure syntax

lazy var game : ConcentrationModel = { 
     return ConcentrationModel(numberOfPairsOfCards: (self.cardButtons.count + 1) / 2) 
}()
vadian
  • 274,689
  • 30
  • 353
  • 361
  • It looks like I don't need the closure, but your example showing the use the keyword self helped. I just added that to my code and it worked. The example in the video and the downloaded example both didn't have the self keyword. So still not sure my difference – owlaf Jan 29 '18 at 21:08
  • I had another issue related to using [swift 4] (https://stackoverflow.com/questions/44379348/the-use-of-swift-3-objc-inference-in-swift-4-mode-is-deprecated). After addressing that I now can even remove the self keyword. Thanks for sending down the right path – owlaf Jan 29 '18 at 21:32