在Swift中,也有控制流,分别是For,For-In,For条件递增,While,Do-While等等,让我们一起来探讨一下:
1.For循环
在Swift中提供两种循环,一种是For-In,另一种是For条件递增,先来看第一种:
for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
// 打印出来的结果:
//1 times 5 is 5
//2 times 5 is 10
//3 times 5 is 15
//4 times 5 is 20
//5 times 5 is 25
如果你不需要知道范围内每一项的值,你可以使用下划线(_)替代变量名来忽略对值的访问:
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
println("\(base) to the power of \(power) is \(answer)")
// 打印出来的结果:3 to the power of 10 is 59049
在前面数组和字典的遍历就已经举过例子了,所以这里就不再列举了.
2.For条件递增
在Swift中,我们也可以使用使用条件递增,只不过和OC有一些区别,现在让我们来看看:
for var index = 0; index < 3; ++index {
println("indx is \(index)")
}
// 打印出来的结果: indx is 0
// indx is 1
// indx is 2
其他的基本上都差不多,知识在Swift中的声明不太一样.
3.While循环
While循环其实和OC也是差不多的,让我们来看看例子:
var square = 0
var diceRoll = 0
let finalSquare = 25
var board = [Int](count: finalSquare + 1,repeatedValue: 0)
while square < finalSquare { if ++diceRoll == 7{ diceRoll = 1 } square += diceRoll if square < board.count { square += board[square] } } println("\(square),\(diceRoll),\(finalSquare)") // 打印出来的结果: 27,3,25
原理基本上都差不多只是有一些细节需要注意一下.
4.Do-While循环
在Swift中的Do-While循环里,和OC中的Do-While差别也不大,让我们来看看例子:
var a = 20
var b = 10
do {
if ++b == a{
a = 0
}
} while a > b
println("\(a),\(b)") // 打印出来的结果: 0,20
5.条件语句
在Swift中,也有判断的条件语句,那就是if,用法和OC一样,没区别,让我们来看看吧:
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
}
// 打印出来的结果: It's very cold. Consider wearing a scarf.
和OC一样,用 if 语句来判断条件,如果条件成立,那么就会返回true,否则就是false.
6.Switch开关
在Swift中的Switch开关非常的好用,和OC不一样,在OC中,如果Switch忘记写break就会报错,但是在Swift中就不需要写这个东西,比如:
let someCharacter: Character = "e"
switch someCharacter {
case "a","e","i","o","u":
println("\(someCharacter) is a vowel")
case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z":
println("\(someCharacter) is a consonant")
default:
println("\(someCharacter) is not a vowel or a consonant")
}
// 打印出来的结果: e is a vowel
在Switch中还可以这么使用:
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a":
break
case "A":
println("The letter A")
default:
println("Not the letter A")
}
// 打印出来的结果: 空的
PS: 在Swift中不存在隐式贯穿,在Swift中,一旦case执行完毕后,就不会继续往下执行,所以也就不需要break了,但如果你的case是空的,那么就必须得写break了,因为在Swift中,Switch的开关必须得有一个内容.
同样的,一个case也可以包含多个模式,比如:
7.范围匹配
let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
naturalCount = "no"
case 1...3:
naturalCount = "a few"
case 4...9:
naturalCount = "several"
case 10...99:
naturalCount = "tens of"
case 100...999:
naturalCount = "hundreds of"
case 1000...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")
// 打印出来的结果:There are millions and millions of stars in the Milky Way.
好了,这次我们就讲到这里,下次我们继续~
@H_352_404@