本章中腐芍,主要涉及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ù)的處理拉背,與上面類似