Swift基础入坑

Swift判断逻辑分支&循环逻辑

2018-06-25  本文已影响11人  iOS_July

一、分支的介绍

tips1、if分支
1>不再有非0`(nil)`即真

2>必须有明确的Bool值

3>Bool的两个取值为: false / true
tips2、guard的使用
1>当条件表达式为true时,跳过else语句中的内容,执行语句组内容
2>当条件表达式为false时,执行else语句中的内容,跳转语句一般为return、break、continue、throw
let age = 18
        
guard age >= 18 else {
    print("年龄不到18,回去吧")
    return
}
print("年龄\(age)可以了,来上网吧")
tips3、switch分支
switch-基本应用
let sex = 0
        
switch sex {
case 0:
     print("男")
case 1:
     print("女")
default:
     print("Other")
}
switch-基本应用补充
let sex = 0
switch sex {
case 0, 1:
    print("正常人")
default:
    print("Other")
}
let m = 13.14

switch m {
case 13.14:
    print("和m相等")
default:
    print("不和m相等")
}
let m = 10
let n = 20
let oprationStr = "*"

var result = 0

switch oprationStr {
case "+":
    result = m + n
case "-":
    result = m - n
case "*":
    result = m * n
case "/":
    result = m / n
default:
    print("不合理操作符")
}
let score = 80

switch score {
case 0..<60:
    print("不合格")
case 60..<80:
    print("合格")
case 80..<90:
    print("良好")
case 90..<100:
    print("优秀")
default:
    print("不合理分数")
}

通常我们指的是数字区间 0-10、100-200
半闭区间 0..<10,表示0-9,不包括10
闭区间 0...10,表示0-10

四、循环介绍

for 循环写法
for number in 0...10 {
    print(number)
    print("打印了11次")
}

用下标 & 不用下标

for _ in 0..<10 {
    print("打印了10次")
}
while和do while循环

while循环

var a = 0
while a < 10 {
    a += 1
}

do while循环

var a = 0
repeat {
    a -= 1
} while a > 0
上一篇 下一篇

猜你喜欢

热点阅读