Swift 学习笔记--switch.for,while

1、switch支持任意类型的数据和大量的比较操作,并不仅仅局限于整型

官方例子

let vegetable = "red pepper"
switch vegetable {
    case "celery":
        print("Add some raisins and make ants on a log.")
    case "cucumber", "watercress":
        print("That would make a good tea sandwich.")
    case let x where x.hasSuffix("pepper"):
        print("Is it a spicy \(x)?")
    default:
        print("Everything tastes good in soup.")
}

 将输出以下结果:

Is it a spicy red pepper?

2、repeat while至少执行一次

var m = 2
repeat {
    m = m * 2
} while m < 100
print(m)

3、for循环中,可以使用..<...表示一个范围

     1..<5      表示 [1,5)

     1...5       表示[1,5]

var total = 0
for i in 1...5{
    total += i
}
print(total)//15\n

 

var total = 0
for i in 1..<5{
    total += i
}
print(total)//10\n

 

猜你喜欢

转载自zhong871004.iteye.com/blog/2286417
今日推荐