標籤:
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 = 010 for score in individualScores {11 if score > 50 {12 teamScore += 313 }else{14 teamScore += 115 }16 }17 18 //可空類型19 //結合if和let,可以方便的處理可空變數(nullable variable)。對於空值,需要在型別宣告後添加?顯示標明該類型可空。20 var optionalString: String? = "Hello"21 optionalString = nil22 23 var optionalName: String? = "John Applesed"24 var gretting = "Hello!"25 if let name = optionalName{26 gretting = "Hello, \(name)"27 }28 29 //靈活的switch30 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 = 050 for(kind, numbers) in interestingNumbers{51 for number in numbers{52 if number > largest{53 largest = number54 }55 }56 }57 58 //while迴圈和do-while迴圈59 var n = 260 while n < 100 {61 n = n * 262 }63 n64 65 var m = 266 do{67 m = m * 268 }while m < 10069 m70 71 72 //Swift支援傳統的for迴圈,此外也可以通過結合..(產生一個區間)和for-in實現同樣的邏輯73 var firstForLoop = 074 for i in 0..3{75 firstForLoop += i76 }77 firstForLoop78 79 var secondForLoop = 080 for var i = 0; i < 3; ++i{81 secondForLoop += 182 }83 secondForLoop84 //注意:Swift除了..還有... 其中..產生前閉後開的區間,而...產生前閉後閉的區間。85 var third = 086 for i in 0...3 {87 third += i88 }89 third
swift基礎文法(控制流程、可選類型、switch、迴圈、開閉空間)