标签:
1 // Playground - noun: a place where people can play 2 3 import Cocoa 4 5 //控制流 6 7 //Swift的条件语句包括if和switch,循环语句包含for-in、for、while和do-while,循环/判断条件不需要括号,但循环/判断体(body)必需括号: 8 let individualScores = [75, 43, 103, 87, 12] 9 var teamScore = 0 10 for score in individualScores { 11 if score > 50 { 12 teamScore += 3 13 }else{ 14 teamScore += 1 15 } 16 } 17 18 //可空类型 19 //结合if和let,可以方便的处理可空变量(nullable variable)。对于空值,需要在类型声明后添加?显示标明该类型可空。 20 var optionalString: String? = "Hello" 21 optionalString = nil 22 23 var optionalName: String? = "John Applesed" 24 var gretting = "Hello!" 25 if let name = optionalName{ 26 gretting = "Hello, \(name)" 27 } 28 29 //灵活的switch 30 let vegetable = "red pepper" 31 switch vegetable { 32 case "celery": 33 let vegetableComment = "Add som raisins and make ants on a log." 34 case "cucumber","watercress": 35 let vegetableComment = "That would make a good tea sandwich." 36 case let x where x.hasSuffix("pepper"): 37 let vegetableComment = "Is it a spicy \(x)?" 38 default: 39 let vegetableComment = "Everything tastes good in soup." 40 } 41 42 //其他循环 43 //for-in 除了遍历数组也可以用来遍历字典 44 let interestingNumbers = [ 45 "Prime":[2,3,5,7,11,13], 46 "Fibonacci":[1,1,2,3,5,8], 47 "Square":[1,4,9,16,25], 48 ] 49 var largest = 0 50 for(kind, numbers) in interestingNumbers{ 51 for number in numbers{ 52 if number > largest{ 53 largest = number 54 } 55 } 56 } 57 58 //while循环和do-while循环 59 var n = 2 60 while n < 100 { 61 n = n * 2 62 } 63 n 64 65 var m = 2 66 do{ 67 m = m * 2 68 }while m < 100 69 m 70 71 72 //Swift支持传统的for循环,此外也可以通过结合..(生成一个区间)和for-in实现同样的逻辑 73 var firstForLoop = 0 74 for i in 0..3{ 75 firstForLoop += i 76 } 77 firstForLoop 78 79 var secondForLoop = 0 80 for var i = 0; i < 3; ++i{ 81 secondForLoop += 1 82 } 83 secondForLoop 84 //注意:Swift除了..还有... 其中..生成前闭后开的区间,而...生成前闭后闭的区间。 85 var third = 0 86 for i in 0...3 { 87 third += i 88 } 89 third
swift基础语法(控制流、可选类型、switch、循环、开闭空间)
标签:
原文地址:http://www.cnblogs.com/lovecc/p/4386062.html