if語句
不需要將正在檢查的表達式放到括號內。
if 1+1 == 2 {
println("The math checks out")
}
所有if語句的主體都要放在大括號內。
if(something)
do_something();
判斷optional類型中是否有值,并賦值給另一個變量
var conditionalString : String? = nil
if let theString = conditionalString {
println("The string is '\(theString)'")
}
else {
println("The string is nil")
}
for循環(huán)
當擁有一個項目集合時,可以使用for-in循環(huán)來迭代每一項。
let loopingArray = [1, 2, 3, 4, 5]
var loopSum = 0
for number in loopingArray {
loopSum += number
}
loopSum // = 15
使用for-in循環(huán)迭代一個數值范圍
var firstCounter = 0
for index in 1 ..< 10 {
firstCounter++
}
//循環(huán)9次
-
number1 ..< number2表示從number1開始到number2的一個范圍(不包含number2)。 -
number1 ... number3表示從number1開始到number2的一個范圍(包含number2)。
也可以像其它語言一樣使用for循環(huán)
while循環(huán)
switch語句
可以像其它語言一樣使用switch語句。
根據元組進行切換
let tupleSwitch = ("Yes", 123)
switch tupleSwitch {
case ("Yes", 123):
println("Tuple contains 'Yes' and '123'")
case ("Yes", _):
println("Tuple contains 'Yes' and something else")
default:
break
}
根據范圍進行切換
var someNumber = 15
switch someNumber {
case 0...10:
println("Number is between 0 and 10")
case 11...20:
println("Number is between 11 and 20")
default:
println("Number is something else")
}