1.循环结构
//for
for index in 1...10{
index//常量
}
for index in 1..<10{
index
}
for i in -99...99{
i*i
}
for var i = -99 ; i <= 99; i++ {
i*i
}
var i = -99
for ; i <= 99; {
i*i
i++
}
//while不知道会执行多少次
//repeat while至少执行一次
var awin = 0
var bwin = 0
var game = 0
while awin < 3 && bwin < 3 {
game++
let a = arc4random_uniform(6)+1
let b = arc4random_uniform(6)+1
//print("a is \(a), b is \(b)." , termimator:" ")
if a > b {
print("A win")
bwin = 0
awin++
}
else if a < b {
print("B win")
awin = 0
bwin++
}
else{
print("draw")
awin = 0
bwin = 0
}
}
let winner = awin == 3 ? "A" : "B"
print("after \(game) games, \(winner) win")
//break continue控制循环的转移
2.选择结构
var rating = "a"
if rating == "A" {
print("A")
}else if rating == "B" {
print("B")
}else {
print("Error")
}
//switch更加灵活,rating的类型比较多,整形,布尔型
switch rating{
case "a", "A":
print("A")
case "b", "B":
print("B")
default:
print("Error")//不要error显示时,可以用break或者空括号()
}
let point = (0,0)//point:(x:Int,y:Int)=(1,1)
switch point{
case (0,0):
print("origin")
fallthrough//可以继续进入下一个case
case (_,0):
print("x-axis")
fallthrough
case (0,_):
print("y-axis")
case (-2...2,-2...2):
print("near point")
default:
print("")
}
switch point{
case (0,0):
print("origin")
case (let x,0):
print("x-axis")
case (0,let y):
print("y-axis")
case (let x, let y):
print("near point")//不需要default
}
//x^4 - y^2 = 15*x*y 只要一组结果,为循环取一个名字
getAnswer:for m in 1...300{
for n in 1...300 {
if m*m*m*m - n*n == 15*m*n {
print(m,n)
break getAnswer
}
}
}
3.where关键字
let point = (3,3)
switch point{
case let(x,y) where x == y:
print("It's on the line x==y")
case let(x,y) where x == -y:
print("It's on the line x==-y")
case let(x,y):
print("The point is (\(x),\(y))")
}
let age = 19
if case 10...19 = age{
print("teenager")
}
if case 10...19 = age where age >= 18{
print("teenager and in a college")
}
let vector = (4,0)
if case (let x,0) = vector where x > 2 && x < 5 {
print("vector")
}
for i in 1...100 {
if i % 3 == 0 {
print(i)
}
}
//等价于
for case let i in 1...100 where i % 3 == 0 {
print(i)
}
4.guard关键字
func buy(money:Int , price:Int , capacity:Int , volume:Int){
if money >= price {
if capacity >= volume {
print("I can buy it")
print("\(money - price) left")
}else{
print("Not enough capacity")
}
}else{
print("Not enough money")
}
}
//等价于
func buy2(money:Int , price:Int , capacity:Int , volume:Int){
guard money >= price else{//guard确保一个的条件,不满足就直接return
print("Not enough money")
return
}
guard capacity >= volume else {//guard确保一个的条件,不满足就直接return
print("Not enough capacity")
return
}
//剩下的就是我们需要的了
print("I can buy it")
print("\(money - price) left")
}