美文网首页
The iOS Apprentice1-10 计算分数

The iOS Apprentice1-10 计算分数

作者: 花开花落花满天 | 来源:发表于2016-04-28 11:28 被阅读0次

本章中,主要涉及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)
    *游戏轮数的处理,与上面类似

相关文章

网友评论

      本文标题:The iOS Apprentice1-10 计算分数

      本文链接:https://www.haomeiwen.com/subject/fuqhrttx.html