The iOS Apprentice1-10 計算分數(shù)

本章中,主要涉及if 判斷語句,var / let 區(qū)別,以及之前內(nèi)容回顧(label的更新)

1. 計算currentValue和targetValue的差值

  • 判斷targetValue 與 currentValue的大小,然后計算差值


    if判斷語句
  • 判斷差值的正負,若為負數(shù),則乘以 -1
var  difValue = currentValue - targetValue
if difValue < 0{
    difValue = difValue * (-1)
  }

*注意上述difValue的定義方式,沒有定義其數(shù)據(jù)類型。swift能夠更加currentValue 和 targetValue的數(shù)據(jù)類型去推斷difValue數(shù)據(jù)類型

This feature is called type inference(類型推斷) and it's one of the big selling points of Swift.

  • 使用內(nèi)建函數(shù)
    let difValue = abs(targetValue - currentValue)

注意上述定義使用的是let ,而之前使用的是var,兩者之間有什么區(qū)別。let定義的是一個常量,而var定義的是一個變量。
The keyword var creates a variable while let creates a constant. That means difference is now a constant, not a variable.

2.添加總分和游戲輪數(shù)

  • 類中添加對應(yīng)的定義
    var score = 0
    @IBOutlet weak var scoreLabel: UILabel!
    *上面score 的定義沒有數(shù)據(jù)類型,因為swift是一種type inference語言,能夠自己根據(jù)0 去推斷score的數(shù)據(jù)類型
  • showAlert中更新score
  • updateLabels() 中添加更新
    scoreLabel.text = String(score)
    *游戲輪數(shù)的處理,與上面類似
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容