我正在关注2017年秋季的Standford ios课程。当教授通过演示时,我会像他一样输入和运行。他展示了如何使用lazy与var允许使用UIButton计数进行变量初始化。当我添加lazy关键字时,错误不会消失。认为这可能是一个xcode更新相关的问题,我下载了其他人的项目版本,该项目没有问题。代码在下面,有什么想法吗? :/
类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)
}
}
}
答案 0 :(得分:0)
要初始化一个依赖于另一个属性值的惰性属性,必须使用闭包语法
lazy var game : ConcentrationModel = {
return ConcentrationModel(numberOfPairsOfCards: (self.cardButtons.count + 1) / 2)
}()