if語(yǔ)句
不需要將正在檢查的表達(dá)式放到括號(hào)內(nèi)胎许。
if 1+1 == 2 {
println("The math checks out")
}
所有if語(yǔ)句的主體都要放在大括號(hào)內(nèi)花竞。
if(something)
do_something();
判斷optional類型中是否有值磷账,并賦值給另一個(gè)變量
var conditionalString : String? = nil
if let theString = conditionalString {
println("The string is '\(theString)'")
}
else {
println("The string is nil")
}
for循環(huán)
當(dāng)擁有一個(gè)項(xiàng)目集合時(shí)喊衫,可以使用for-in
循環(huán)來(lái)迭代每一項(xiàng)铛只。
let loopingArray = [1, 2, 3, 4, 5]
var loopSum = 0
for number in loopingArray {
loopSum += number
}
loopSum // = 15
使用for-in
循環(huán)迭代一個(gè)數(shù)值范圍
var firstCounter = 0
for index in 1 ..< 10 {
firstCounter++
}
//循環(huán)9次
-
number1 ..< number2
表示從number1開(kāi)始到number2的一個(gè)范圍(不包含number2)世剖。 -
number1 ... number3
表示從number1開(kāi)始到number2的一個(gè)范圍(包含number2)定罢。
也可以像其它語(yǔ)言一樣使用for
循環(huán)
while循環(huán)
switch語(yǔ)句
可以像其它語(yǔ)言一樣使用switch
語(yǔ)句。
根據(jù)元組進(jìn)行切換
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
}
根據(jù)范圍進(jìn)行切換
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")
}