The iOS Apprentice1-10 计算分数

本章中,主要涉及if 判断语句,var / let 区别,以及之前内容回顾(label的更新)

1. 计算currentValue和targetValue的差值

  • 判断targetValue 与 currentValue的大小,然后计算差值


    if判断语句
  • 判断差值的正负,若为负数,则乘以 -1
var  difValue = currentValue - targetValue
if difValue < 0{
    difValue = difValue * (-1)
  }

*注意上述difValue的定义方式,没有定义其数据类型。swift能够更加currentValue 和 targetValue的数据类型去推断difValue数据类型

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

  • 使用内建函数
    let difValue = abs(targetValue - currentValue)

注意上述定义使用的是let ,而之前使用的是var,两者之间有什么区别。let定义的是一个常量,而var定义的是一个变量。
The keyword var creates a variable while let creates a constant. That means difference is now a constant, not a variable.

2.添加总分和游戏轮数

  • 类中添加对应的定义
    var score = 0
    @IBOutlet weak var scoreLabel: UILabel!
    *上面score 的定义没有数据类型,因为swift是一种type inference语言,能够自己根据0 去推断score的数据类型
  • showAlert中更新score
  • updateLabels() 中添加更新
    scoreLabel.text = String(score)
    *游戏轮数的处理,与上面类似
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容