加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift基本使用-控制流(二)

发布时间:2020-12-14 02:02:59 所属栏目:百科 来源:网络整理
导读:控制流,同其他语言,if和switch用来进行条件判断操作,使用for-in、for、while和do-while处理循环操作。swift中条件的括号可以省略,语句块儿的括号必须存在。 var pass: NSMutableArray = [] var fail: NSMutableArray = [] let scores = [ 59 , 40 , 79 ,

控制流,同其他语言,if和switch用来进行条件判断操作,使用for-in、for、while和do-while处理循环操作。swift中条件的括号可以省略,语句块儿的括号必须存在。

var pass: NSMutableArray = []
var fail: NSMutableArray = []
let scores = [59,40,79,100,61,99]
for score in scores {
    if score > 60 {
        pass.addObject(score)
    } else {
        fail.addObject(score)
    }
}
println(pass)
println(fail)

在swift中,条件的判断必须是布尔值,如下判断的方式是错的,在Object-c中可以直接判断对象是否为nil,swift却是错的。
错误的写法

var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
if !cell {
}

正确的写法

if cell != nil {
    cell = UITableViewCell(style: UITableViewCellStyle.Default,reuseIdentifier: "cell") as UITableViewCell
}

swift中switch支持任意类型的数据以及各种比较操作,不再只是整数类型的相等。

let colorString: String = "red"
var color: UIColor? = nil
switch colorString {
    case "red":
    color = UIColor.redColor()
    break
case "green":
    color = UIColor.greenColor()
    break
case "yellow":
    color = UIColor.yellowColor()
    break
default:
    color = UIColor.blackColor()
}

可以用for-in遍历数组或者字典,遍历字典的时候需要两个变量来分别表示键值对。

let dict = [
    "LiaoNing": "ShenYang","HeBei":"ShiJiazhuang",]
//println
for (province,city) in dict {
    println("(city) belong to (province)")
}

使用while来做重复运算,知道条件不满足,循环结束。条件可以在开始也可以在结尾处。

var i = 0
while i < 10 { i = i + 1 }
do { i = i - 1 } while i > 0

在for循环中,也可以用..来表示范围,传统的for-in也可以,两者相同:

var count = 0
for i in 0..10 {
    count = count + i
}
//same to
for var i = 0; i< 10; ++i {
    count = count + i
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读