码迷,mamicode.com
首页 > 其他好文 > 详细

Swift控制流

时间:2014-06-06 09:15:21      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

概览

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

bubuko.com,布布扣
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 }
bubuko.com,布布扣

可空类型

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

bubuko.com,布布扣
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 }
bubuko.com,布布扣

灵活的 switch

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

bubuko.com,布布扣
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 }
bubuko.com,布布扣

其它循环

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

bubuko.com,布布扣
 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
bubuko.com,布布扣

while循环和do-while循环:

bubuko.com,布布扣
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
bubuko.com,布布扣

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

bubuko.com,布布扣
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
bubuko.com,布布扣

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

 

Swift控制流,布布扣,bubuko.com

Swift控制流

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/atong/p/3767435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!