for num in 1..<5 {
print(num)
}
//九九乘法表
for time in 1...9 {
for num in 1...time {
print("\(num) times \(time) is \(time * num)")
}
}
//不需要参数,用_代替值
for _ in 1...10 {
print("这是个循环")
}
var i = 0
while i<10 {
i += 1
}
repeat {
i += 1
}while i<20
var hour = 18
if hour < 6 {
print("现在是凌晨")
}else if hour < 12 {
print("现在是早上")
}else if hour < 18 {
print("现在是中午")
}else {
print("现在是晚上")
}
- Switch
var day = "Monday"
switch day {
case "Monday":
print("周一")
case "Tuesday":
print("周二")
case "Wednesday":
print("周三")
case "Thursday":
print("周四")
case "Friday":
print("周五")
case "Saturday":
print("周六")
case "Sunday":
print("周日")
default:
print("error")
}
var day = "Monday"
switch day {
case "Monday","Tuesday","Wednesday","Thursday","Friday":
print("工作日")
case "Sunday","Sunday":
print("周末")
default:
print("error")
}
var score = 60
switch score {
case 0..<60:
print("不及格")
case 60..<75:
print("及格")
case 75..<90:
print("良好")
case 90...100:
print("优秀")
default:
print("不存在的")
}
- 元组复合匹配(若做复合匹配,则两个值必须为同类型,且变量名必须相等)
var code = "404"
var response = ("404","Not Found")
switch response {
case (let code,"Not Found"),("404",let code):
print("请求失败")
case (let code,"success "),("200",let code):
print("请求成功")
default:
print("未知错误")
}
- 控制转移语句
- Continue(跳出当前循环,进行下次循环)
var i = 0
for number in 1...10 {
if number == 5 {
continue
}
//此处i只加了9次,因为当number等于5时,跳出了当前循环
i += number
}
- Break(跳出整个循环,或者作为Switch语句中的忽略语句,Swift中的Switch,每个分支都必须有相应的操作,当我们想忽略这个分支时,可以用Break)
var i = 0
for number in 1...10 {
if number == 5 {
break
}
//此处i只加了4次,因为当number等于5时,循环结束了
i += number
}
var day = "Monday"
switch day {
case "Monday":
print("周一")
case "Tuesday":
print("周二")
case "Wednesday":
print("周三")
case "Thursday":
print("周四")
case "Friday":
print("周五")
case "Saturday":
print("周六")
case "Sunday":
print("周日")
default:
break
}
- Fallthrough(贯穿,switch条件中,执行完当前分支语句后,即使不符合下一分支条件,也会继续执行下一分支)
var day = "Monday"
switch day {
case "Monday":
print("周一要")
fallthrough
default:
print("上班")
}
- 带标签的控制语句,在Swift中,我们可以使用一个标签给循环或者条件控制语句命名,方便嵌套时操作对应循环或者条件控制,下述例子中,i只加了4次,因为在第二层循环中,time为5时,跳出了本次循环,进入下一循环,同时time为6时,跳出了firstLoop主循环
var i = 0
firstLoop : for number in 1...10 {
secondLoop : for time in 1...10
{
if time == 5 {
continue secondLoop
}
if time == 6 {
break firstLoop
}
i += time
}
}
- return(用在方法中,用于调出方法),guard语句,类似于if,提供一个判断,若为假,执行else后的语句,通常使用此方法,在判断某个值时,作为跳出某个方法的依据
var i = 5
func greaterThanZero(number:Int) {
guard number > 0 else {
return
}
print("数字\(number)大于0")
}
greaterThanZero(number: i)