if
()
,要使用也可以。Bool
。{}
。else
執行否定敘述。var happyness = true
if happyness {
println("😀") //return: "😀"
} else {
println("😢")
}
&&
或||
。var weekend = true
var sunny = true
if weekend && sunny {
var mood = "😄" //return: "😄"
}
switch
()
,要用也可以。case
,加上處理的敘述。case
,或是使用default
捕捉剩下的情況。var score = 0
switch score {
case 0:
"白癡" //retunr: "白癡"
case 100:
"天才"
default:
"平凡人"
}
case
不需break
可自動跳出switch
。case
不做任何事必須使用break
。fallthrough
不離開switch
繼續執行下個case
。var score = 0
switch score {
case 0:
fallthrough
case 100:
"天才白痴一線間" //return: "天才白痴一線間"
default:
break
}
var grade = 100
switch grade {
case 0, 100:
"天才白痴一線間" //return: "天才白痴一線間"
default:
"平凡人"
}
var fruit = "蘋果"
switch fruit {
case "蘋果":
"好吃" //return: "好吃"
case "榴槤":
"噁心"
default:
"還好"
}
for
()
,要用也可以。Bool
。&&
或||
。{}
不能省略。var num: Int
。for var num = 0; num < 3; num++ {
"hello world"
}
()
。{}
不能省略。let friend: String
。var friends = ["Eddy", "Gary", "Jimmy"]
for friend in friends {
println("Hi, \(friend)!")
}
while
var num = 0
while num < 10 {
print("\(num)")
num += 1
}
//output: 0123456789
var num = 0
do {
print("\(num)")
num += 1
} while num < 10
//output: 0123456789
Swift2 修改 do-while 語法,改用 repeat-while。
for num in 1...5 {
print(num)
} //output: 12345
for num in 1..
from
。through
(包含終點),to
(不含終點)。for num in stride(from: 9, through: 1, by: -2) {
print(num)
} //output: 97531
for num in stride(from: 9, to: 1, by: -2) {
print(num)
} //output: 9753
switch
+ Rangevar score = 65
switch score {
case 0..<60: "E"
case 60..<70: "D" //output: "D"
case 70..<80: "C"
case 80..<90: "B"
case 90...100: "A"
default: "?"
}
for-in
+ Rangefor num in 1...5 {
print(num)
} //output: 12345