swift 控制流(条件语句、循环语句、控制转向语句)

这是我参与更文挑战的第6天,活动详情查看: 更文挑战

条件语句(if 语句switch 语句

if 语句

  • if 单分支结构
let temperature = 28
if temperature <= 25 {
    print("温度较低")
} 
复制代码
  • if 双分选择支结构
let temperature = 28
if temperature <= 25 {
    print("温度较低")
} else if temperature >= 30 {
    print("温度较高")
} 
复制代码
  • if 多分支选择结构
let temperature = 28
if temperature <= 25 {
    print("温度较低")
} else if temperature >= 30 {
    print("温度较高")
} else {
    print("温度刚好")
}
复制代码

switch 语句

通常判断条件的分支大于3种,继续使用if-else代码看起来冗长且逻辑层次过多,这个时候可以考虑switch语句

let phoneType = "apple"

switch phoneType {
case "huawei":
    print("华为")
case "apple":
    print("苹果")
case "xiaomi":
    print("小米")
default:
    print("其他手机")
}
复制代码
  • swift中,不需要显式地使用break语句

    在OC中,switchcase中如果不写break,则会把匹配项以下的每一个case都执行,而在swift中,只要找到第一个匹配项的case,程序会就会终止switch语句,而不会继续执行下一个case分支

let phoneType = "apple"

switch phoneType {
case "huawei":
    print("华为")
case "apple":
    print("苹果")
case "xiaomi":
    print("小米")
default:
    print("其他手机")
}

log:
苹果
复制代码
  • 当多个条件可以使用同一种方法来处理时,可以将这几种可能放在同一个case后面,并且用逗号隔开
let phoneType = "xiaomi"

switch phoneType {
case "huawei","xiaomi","oppo":
    print("中国手机")
case "apple","google":
    print("美国手机")
case "samsung":
    print("韩国手机")
default:
    print("其他手机")
}

log:
中国手机
复制代码
  • switch语句可以检测其判断的值,是否包含在某个case的范围内。
let value = 25
switch value {
case 10:
    print("value = 10")
case 20 ..< 40:
    print("20 < value < 40")
case 50:
    print("value = 50")
default:
    print(value)
}

log
20 < value < 40
复制代码
  • switch语句可以判断元组的值。元组中的元素可以是值,也可以是区间。另外,使用下划线(_)来匹配所有值
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) 原点")
case (_, 0):
    print("\(somePoint) 在x轴上")
case (0, _):
    print("\(somePoint) 在y轴上")
case (-2...2, -2...2):
    print("\(somePoint) 在区域里")
default:
    print("\(somePoint) 在区域外")
}

log:
(1, 1) 在区域里
复制代码
  • case分支允许将匹配的值声明为临时常量或变量,并且在case分支体内使用,这种行为称为值绑定
let anotherPoint = (0, 2)
switch anotherPoint {
case (let x, 0):
    print("x 轴的值是 \(x)")
case (0, let y):
    print("y 轴的值是 \(y)")
case let (x, y):
    print("点的坐标是 (\(x), \(y))")
}

log:
y 轴的值是 2
复制代码
  • 可以使用where语句来判断额外的条件
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    print("(\(x), \(y)) 在 x == y线上")
case let (x, y) where x == -y:
    print("(\(x), \(y)) 在 x == -y 线上")
case let (x, y):
    print("(\(x), \(y)) 只是任意一点")
}

log:
(1, -1) 在 x == -y 线上
复制代码

循环语句 (for-inwhilerepeat-While

for-in语句

  • for-in循环迭代数组
let arr = ["A","B","C"]
for str in arr {
    print(str);
}

log:
A
B
C
复制代码
  • for-in循环迭代字典
let dic = ["keyA":"a","keyB":"b"]
for (key,value) in dic {
    print("\(key)---\(value)")
}

log:
keyA---a
keyB---b
复制代码
  • for-in循环迭代数值范围
for index in 1 ..< 3 {
    print(index)
}

log:
1
2
复制代码
  • 如果不需要范围中的每个值,可以使用下划线(_)代替变量名来忽略这些值
var a = 2
let b = 3
for _ in 1 ... b {
    a += b
}
print(a)

log:11
复制代码
  • 可跳过不需要的打印的值
    • stride(from:to:by:)封闭范围是个开区间

      for value in stride(from: 0, to: 10, by: 2) {
          print(value)
      }
      
      log:
      0    2   4   6   8
      复制代码
    • stride(from:through:by:)封闭范围是个闭区间

      for value in stride(from: 0, through: 10, by: 2) {
          print(value)
      }
          
      log:
      0    2   4   6   8    10
      复制代码

while语句

  • while循环

    每次在循环开始时计算条件表达式,如果表达式值为true,才会执行循环体。执行完循环体之后再进行条件表达式判断,直到条件为false循环才会终止

var a = 3
while a > 0 {
    a -= 1
    print(a)  //2  1  0
}

log:
2
1
0
复制代码
  • repeat-while循环

    repeat-while循环的变体,类似于其他语言中的do-while,当执行这一个循环结构时,会先执行一次循环,再判断循环条件表达式,然后重复循环,直到表达式为false循环才会终止

var a = 0
repeat {
    a += 1
    print(a)  
} while a < 3

log:
1 
2 
3
复制代码

控制转向语句(continuebreakfallthroughreturnthrow)

continue : 终止本次循环,重新开始下次循环

for i in 0 ..< 5 {
    if i == 2 {
        continue
    }
    print("i = \(i)")
}

log:
i = 0
i = 1
i = 3
i = 4
复制代码

break : 终止整个循环的执行

for i in 0 ..< 5 {
    if i == 2 {
        break
    }
    print("i = \(i)")
}

log:
i = 0
i = 1
复制代码

fallthrough

由于swift语言中的switch只要第一个匹配到的case分支完成了执行语句,整个switch代码块就会完成它的执行,而不需要你显示的插入break语句,而OC语句则可能在没有插入break语句的情况下执行以下多个case分支,如果需要实现同OC相同的特性,在这里可以用fallthrough语句

let flag = 5
var description = "北京"
switch flag {
case 5:
    description += "的"
    fallthrough
case 10:
    description += "冬天"
default:
    description += "全是霾"
}
print(description)  

log
北京的冬天
复制代码

return、throw 跳出作用域

func showValue() {
    for i in 0 ..< 5 {
        print("i = \(i)")
        if i == 2 {
            return
        }
    }
}
print(showValue())

log:
i = 0
i = 1
i = 2
复制代码

guard…else

  • 能使用if...else的地方都能使用guard...else,但是反过来未必。guard一定要和else一起使用,而且使用的地方也必须是在函数中
  • 当判断语句的条件满足的时候,就会去执行语句组,但是在不满足的情况下,就会去执行else中的语句,并且必须写上breakreturncontinuethrow等关键字作为结束符
class Student: NSObject {
    func showScore(score:Int) {
        guard score >= 60 else {
            print("考试不及格")
            return
        }
        print(score)
    }
}
let student = Student()
student.showScore(score: 50)

log:
考试不及格
复制代码

检测API可用性

  • Swift支持检查API可用性,这可以确保我们不会在当前部署机器上,不小心地使用了不可用的API
if #available(iOS 10, macOS 10.12, *) {
    // Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
} else {
    // Fall back to earlier iOS and macOS APIs
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享