1 // https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2-XID_1 2 3 // let implicitInteger = 70 4 // let implicitDouble = 70.0 5 // let explicitDouble: Double = 70 6 // 7 // 8 // 9 // let label = "The width is " 10 // let width = 94 11 // let widthLabel = label + String(width) 12 13 14 15 var shoppingList = ["catfish", "water", "tulips", "blue paint"] 16 shoppingList[1] = "bottle of water" 17 var occupations = [ 18 // "Malcolm": "Captain", 19 "Kaylee": "Mechanic", 20 ] 21 /* occupations["Jayne"] = "Public Relations" */ 22 23 24 25 let individualScores = [75, 43, 103, 87, 12] 26 var teamScore = 0 27 for score in individualScores { 28 if score > 50 { 29 teamScore += 3 30 } else { 31 teamScore += 1 32 } 33 } 34 teamScore 35 36 37 38 var optionalString: String? = "Hello" 39 optionalString == nil 40 var optionalName: String? = "John Appleseed" 41 var greeting = "Hello!" 42 if let name = optionalName { 43 greeting = "Hello, \(name)" 44 } 45 46 47 48 let vegetable = "red pepper" 49 switch vegetable { 50 case "celery": 51 let vegetableComment = "Add some raisins and make ants on a log." 52 case "cucumber", "watercress": 53 let vegetableComment = "That would make a good tea sandwich." 54 case let x where x.hasSuffix("pepper"): 55 let vegetableComment = "Is it a spicy \(x)?" 56 default: 57 let vegetableComment = "Everything tastes good in soup." 58 } 59 60 61 62 let interestingNumbers = [ 63 "Prime": [2, 3, 5, 7, 11, 13], 64 "Fibonacci": [1, 1, 2, 3, 5, 8], 65 "Square": [1, 4, 9, 16, 25], 66 ] 67 var largest = 0 68 for (kind, numbers) in interestingNumbers { 69 for number in numbers { 70 if number > largest { 71 largest = number 72 } 73 } 74 } 75 largest 76 77 78 hasAnyMatchesnull79 func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { 80 for item in list { 81 if condition(item) { 82 return true 83 } 84 } 85 return false 86 } lessThanTennull87 func lessThanTen(number: Int) -> Bool { 88 return number < 10 89 } 90 var numbers = [20, 19, 7, 12] 91 hasAnyMatches(numbers, lessThanTen) /* 92 Functions are actually a special case of closures. You can write a closure without a name by surrounding code with braces ({}). Use in to separate the arguments and return type from the body. */ 93 94 numbers.map({ 95 (number: Int) -> Int in 96 let result = 3 * number 97 return result 98 }) 99 100 101 102