【问题标题】:Having trouble using lazy with a var in swift在 swift 中使用惰性和 var 时遇到问题
【发布时间】:2018-07-08 15:37:45
【问题描述】:

我正在关注 2017 年秋季的斯坦福 ios 课程。当教授进行演示时,我像他一样进行输入和运行。他展示了如何将惰性与 var 一起使用允许使用 UIButton 计数进行变量初始化。当我添加惰性关键字时,错误并没有消失。认为这可能是与 xcode 更新相关的问题,我下载了其他人的项目版本,该项目没有问题。代码如下,有什么想法吗? :/

类视图控制器: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)
    }
}

}

【问题讨论】:

    标签: ios swift3


    【解决方案1】:

    要初始化依赖于另一个属性值的惰性属性,您必须使用闭包语法

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

    【讨论】:

    • 看起来我不需要闭包,但是您的示例显示使用关键字 self 有所帮助。我刚刚将它添加到我的代码中并且它有效。视频中的示例和下载的示例都没有 self 关键字。所以还是不确定我的区别
    • 我遇到了另一个与使用 [swift 4] (stackoverflow.com/questions/44379348/…) 相关的问题。解决这个问题后,我现在甚至可以删除 self 关键字。感谢您发送正确的路径
    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 2014-12-07
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多