1. for 循环
Swift 中提供了 for-in 循环
var num1,num2//这里假设num1 <= num2
for index in num1 ... num2 {
}//这个循环执行了 (num2 - num1 + 1) 次
for index in num1 ..< num2 {
}//这个循环执行了 (num2 - num1) 次
当 for-in 循环运用在字符串中
var count=0
let name = "Jonny"
for char in name.characters {
if char == "n" {
count += 1
}
print(count)//结果 : 2
当 for-in 循环运用在数组中
let students = ["Jerry", "Thomas", "John"]
var studentNumber = 0
for student in students {
studentNumber += 1
}
print(studentNumber)//结果 : 3
当 for-in 循环运用在字典中
let studentsScore = ["Jerry": 78, "Thomas" : 90, "John" : 88]
for (student, score) in studentsScore {
print("\(student) 的分数为 \(score)")
}
/*结果 :
John 的分数为 88
Thomas 的分数为 90
Jerry 的分数为 78
*/
2. while 循环语句
while 循环语句模板 :
var index = 0
while index < 3 {
index += 1
print("循环执行了一次")
}
print(index)
/*结果:
循环执行了一次
循环执行了一次
循环执行了一次
3
*/
3. repeat-while 循环语句
repeat-while 循环语句模板 :
var index = 0
repeat {
index += 1
print("循环执行了一次")
}
while index < 3
print(index)
/*结果:
循环执行了一次
循环执行了一次
循环执行了一次
3
*/
4. if 条件判断语句
在 Swift 的 if 条件判断语句中, 大括号是强制使用的
let password1 = "123456"
let password2 = "1234567"
var userType = "12345678"
if userType == password1 {
print("密码输入正确")
}
if userType == password1 {
print("密码输入正确")
}
else {
print("密码输入错误")
}
if userType == password1 {
print("密码输入正确")
}
else if userType == password2 {
print("密码输入正确")
}
else {
print("密码输入错误")
}
if userType == password1 || userType == password2 {
print("密码输入正确")
}
else {
print("密码输入错误")
}
/*结果:
密码输入错误
密码输入错误
密码输入错误
*/
5. switch 条件判断语句
Swift 的 switch 语句并不会从一个 case 分支跳转到下一个 case 分支, 只要匹配到一个 case 分支, 就完成了整个 switch 语句
Switch 语句中, 至少有一个 case 语句
在 case 语句中, 当某个区间的值的语句都是一样的时候, 在 Swift 中, 可以用 minNumber ..< maxNumber 或者 minNumber ... maxNumber 去代替
当某些值没有完全覆盖的时候, 可以用 default 语句去覆盖这些没有写入条件的值
default 语句必须放在 switch 语句分支的最后
let time = 14
switch time {
case0 ..< 8 :
print("休息时间")
case8, 12, 18 :
print("吃饭时间")
case let x where x > 18 && x <= 24 :
print("娱乐时间")
default :
print("工作时间")
}
//结果 : 工作时间
如果想要执行完一个 case 分支, 跳转到特定的另外一个分支继续判断, 可以在最后添加一个 fallthrough 语句
但是 fallthrough 语句之后的 case 分支的条件中不可以定义常量或者变量
在一个 case 分支中, 如果存在 fallthrough 语句, fallthrough 语句之后的语句将不再执行, 而是直接跳到下一个 case 分支执行
let time = 3
switch time {
case 0 ..< 8 :
print("休息时间")
fallthrough
print("请注意休息!")
case 8, 12, 18 :
print("吃饭时间")
case let x where x > 18 && x <= 24 :
print("娱乐时间")
default :
print("工作时间")
}
/*结果:
休息时间
吃饭时间
*/
6. continue 语句
Swift 的 continue 语句是用来停止循环体的本次循环, 并且立即进入下一次循环
let studentGender = ["男", "女", "男", "女", "女", "男", "男", "男"]
var boysNumber = 0
for gender in studentGender{
if gender == "女" {
continue
}
boysNumber+=1
}
print(boysNumber)//结果 : 5
自創文章, 原著 : Jonny, 如若需要轉發, 在已經授權的情況下請註明出處 :《Swift 第三课 : 循环和条件判断》https://jonny.vip/2017/07/05/swift-%e7%ac%ac%e4%b8%89%e8%af%be-%e5%be%aa%e7%8e%af%e5%92%8c%e6%9d%a1%e4%bb%b6%e5%88%a4%e6%96%ad/
Leave a Reply