• 周二. 9月 27th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Swift控制流

admin

11月 28, 2021

概览

  Swift 的条件语句包含ifswitch,循环语句包含for-inforwhiledo-while,循环/判断条件不需要括号,但循环/判断体(body)必需括号:

1 let individualScores = [75, 43, 103, 87, 12]
2 var teamScore = 0 for score in individualScores {
3     if score > 50 {
4         teamScore += 3
5     } else {
6         teamScore += 1
7     }
8 }

可空类型

  结合iflet,可以方便的处理可空变量(nullable variable)。对于空值,需要在类型声明后添加?显式标明该类型可空。

1 var optionalString: String? = "Hello"
2 optionalString == nil
3 
4 var optionalName: String? = "John Appleseed" var gretting = "Hello!" if let name = optionalName {
5     gretting = "Hello, (name)"
6 }

灵活的 switch

  Swift 中的switch支持各种各样的比较操作:

1 let vegetable = "red pepper" switch vegetable {
2 case "celery":
3     let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress":
4     let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix ("pepper"):
5     let vegetableComment = "Is it a spicy (x)?" default:
6     let vegetableComment = "Everything tastes good in soup."
7 }

其它循环

  for-in除了遍历数组也可以用来遍历字典:

 1 let interestingNumbers = [
 2     "Prime": [2, 3, 5, 7, 11, 13],
 3     "Fibonacci": [1, 1, 2, 3, 5, 8],
 4     "Square": [1, 4, 9, 16, 25],
 5 ]
 6 var largest = 0 for (kind, numbers) in interestingNumbers {
 7     for number in numbers {
 8         if number > largest {
 9             largest = number
10         }
11     }
12 }
13 largest

while循环和do-while循环:

1 var n = 2 while n < 100 {
2     n = n * 2
3 }
4 n
5 
6 var m = 2 do {
7     m = m * 2
8 } while m < 100
9 m

Swift 支持传统的for循环,此外也可以通过结合..(生成一个区间)和for-in实现同样的逻辑。

1 var firstForLoop = 0 for i in 0..3 {
2     firstForLoop += i
3 }
4 firstForLoop
5 
6 var secondForLoop = 0 for var i = 0; i < 3; ++i {
7     secondForLoop += 1
8 }
9 secondForLoop

注意:Swift 除了..还有.....生成前闭后开的区间,而...生成前闭后闭的区间。

发表回复

您的电子邮箱地址不会被公开。