swift 中的循環(huán)控制語法跟 oc 比較有些不同囊骤,循環(huán)體可以使用開閉區(qū)間來進(jìn)行控制循環(huán)體偷线,穿插使用 switch 進(jìn)行類型匹配
// 循環(huán)控制
for _ in 1...5 {
print("Li")
}
// 開
for i in stride(from: 0, to: 50, by: 5) {
print(i)
}
// 閉
for i in stride(from: 0, through: 50, by: 5) {
print(i)
}
// while 循環(huán) 使用 repeat
var count = 0
repeat {
print(count)
count += 1;
}while count < 5
// Switch fallthrough 保存隱式貫穿
let number = 10
switch number {
case 1:
print("1");
fallthrough
case 2:
print("2");
// fallthrough
case 1...2:
print("包含");
// fallthrough
default:
print("other")
}
// 匹配元組
let ay = (1,1)
switch ay {
case (0,1):
print("this is box")
case(_ , 0):
print("this is box")
case(1,0):
print("")
case (1,1):
print("there")
default:
print("other")
}
// switch 綁定值
let ay = (1,1)
switch ay {
case (let y,1):
print(" this is \(y)")
default:
print("other")
}
var number = 10
whileLoop: while number > 0 {
switch number {
case 9:
print("9")
case 10:
var sum = 0
for i in 1...10 {
sum += 1;
if i == 9 {
print(sum)
break whileLoop
}
}
default:
break
}
}
number -= 1
// guard 只有在條件為假的情況下進(jìn)入≥
let isDebug = false
guard isDebug else {
print("isDebug");
return
}
// 類型匹配
/*
struct Dog : Animal {
var name: String {
return "dog"
}
var runSpeed: Int
}
struct Bird : Animal {
var name: String {
return "bird"
}
var speed: Int
}
struct Fish : Animal {
var name: String {
return "fish"
}
var depth: Int
}
let animals:[Any] = [Dog(runSpeed: 220),Bird(speed: 220),Fish(depth: 1200)]
for animal in animals {
switch animal {
case let dog as Dog:
print("dog\(dog.runSpeed)")
case let bird as Bird:
print("bird \(bird.speed)")
case let fish as Fish:
print(fish.depth)
default:
break;
}
}
let teacher = Teacher(salary: 1000, name: "jonny")
switch teacher {
case 0..<2000:
print("溫飽")
case 2000..<5000:
print("小康")
case 5000..<10000:
print("滋潤")
default:
break
}