Swift基础学习(三)《The Swift Programming Language 中文版》前言部分代码示例
1 import UIKit 2 3 var str = "Hello, playground" 4 5 var myVariable = 42 6 myVariable = 50 7 let myConstant = 42 8 9 let implicitInteger = 70 10 let implicitDouble = 70.0 11 let explicitDouble: Double = 70 12 let explicitFloat: Float = 4 13 14 let label = "The width is" 15 let width = 94 16 let widthLabel = label + String(width) 17 18 let apples = 3 19 let oranges = 5 20 let appleSummary = "I have \(apples) apples." 21 let fruitSummary = "I have \(apples + oranges) pieces of fruit." 22 23 let float1 = 1.0 24 let float2 = 3.0 25 let floatString = "\(float1 + float2) CHM, Hi" 26 27 var shoppingList = ["catfish", "water", "tulips", "blue paint"] 28 shoppingList[1] = "bottle of water" 29 30 var occupations = [ 31 "Malcolm": "Captain", 32 "Kaylee": "Mechanic", 33 ] 34 occupations["Jayne"] = "public Relations" 35 36 let emptyArray = [String]() 37 let emptyDictionary = [String: Float]() 38 shoppingList = [] 39 occupations = [:] 40 41 let individualScores = [75, 43, 103, 87, 12] 42 var teamScore = 0 43 for score in individualScores { 44 if score > 50 { 45 teamScore += 3 46 } else { 47 teamScore += 1 48 } 49 } 50 print(teamScore) 51 52 var optionalString: String? = "Hello" 53 print(optionalString == nil) 54 55 var optionalName: String? = nil 56 var greeting = "Hello!" 57 58 if let name = optionalName { 59 greeting = "Hello, \(name)" 60 } else { 61 greeting = "Hello, CHM" 62 } 63 64 let nickName: String? = nil 65 let fullName: String = "John Appleseed" 66 let informalGreeting = "Hi \(nickName ?? fullName)" 67 68 let vegetable = "red pepper" 69 switch vegetable { 70 case "celery": 71 print("Add some raisins and make ants on a log") 72 case "cucumber", "watercress": 73 print("That would make a good tea sandwich.") 74 case let x where x.hasSuffix("pepper"): 75 print("Is it a spicy \(x)?") 76 default: 77 print("Everything tastes good in soup.") 78 } 79 80 let interestingNumbers = [ 81 "Prime": [2, 3, 5, 7, 11, 13], 82 "Fibonacci": [1, 1, 2, 3, 5, 8], 83 "Square": [1, 4, 9, 16, 25], 84 ] 85 86 var largest = 0 87 var largestKind = "" 88 for (kind, numbers) in interestingNumbers { 89 for number in numbers { 90 if number > largest { 91 largest = number 92 largestKind = kind 93 } 94 } 95 } 96 97 print("\(largest, largestKind)") 98 99 var n = 2 100 while n < 100 { 101 n = n * 2 102 } 103 print(n) 104 105 var m = 2 106 repeat { 107 m = m * 2 108 } while m < 100 109 print(m) 110 111 var total = 0 112 for i in 0..<4 { 113 total += i 114 } 115 print(total) 116 117 func greet(person: String, day: String) -> String { 118 return "Hello \(person), today is \(day)." 119 } 120 greet(person: "Bob", day: "Thesday") 121 122 func eat(name: String, food: String) -> String { 123 return "\(name) eat \(food) today." 124 } 125 126 func greet(_ person: String, on day: String) -> String { 127 return "Hello \(person), today is \(day)." 128 } 129 greet("John", on: "Wednesday") 130 131 func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { 132 var min = scores[0] 133 var max = scores[0] 134 var sum = 0 135 136 for score in scores { 137 if score > max { 138 max = score 139 } else if score < min { 140 min = score 141 } 142 sum += score 143 } 144 145 return(min, max, sum) 146 } 147 148 let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9]) 149 print(statistics.sum) 150 print(statistics.2) 151 152 func sumOf(numbers: Int...) -> Int { 153 var sum = 0 154 for number in numbers { 155 sum += number 156 } 157 return sum 158 } 159 160 sumOf() 161 sumOf(numbers: 42, 597, 12) 162 163 164 func returnFifteen() -> Int { 165 var y = 0 166 func add() { 167 y += 5 168 } 169 add() 170 return y 171 } 172 returnFifteen() 173 174 func makeIncrementer() -> ((Int)-> Int) { 175 func addOne(number: Int) -> Int { 176 return 1 + number 177 } 178 return addOne 179 } 180 181 var increment = makeIncrementer() 182 increment(7) 183 184 func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Int { 185 for item in list { 186 if condition(item) { 187 return item 188 } 189 } 190 return 0 191 } 192 193 func lessThanTen(number: Int) -> Bool { 194 return number < 10 195 } 196 197 var numbers = [20, 19, 7, 12] 198 hasAnyMatches(list: numbers, condition: lessThanTen) 199 200 numbers.map({ 201 (number: Int) -> Int in 202 let result = 3 * number 203 return result 204 }) 205 206 let mappedNumbers = numbers.map({number in 3 * number}) 207 print(mappedNumbers) 208 209 //let sortedNumbers = numbers.sort{$0 > $1} 210 //print(sortedNumbers) 211 212 class Shape { 213 var numberOfSides = 0 214 let addLetCode = 0 215 func simpleDescription() -> String { 216 return "A shape with \(numberOfSides) sides." 217 } 218 219 func addLetCodeTest(par: Int) -> String { 220 return "a \(par) sides." 221 } 222 } 223 224 var shape = Shape() 225 shape.numberOfSides = 7 226 var shapeDescription = shape.simpleDescription() 227 228 class NamedShape { 229 var numberOfSides: Int = 0 230 var name: String 231 232 init(name: String) { 233 self.name = name 234 } 235 236 func simpleDescription() -> String { 237 return "A shape with \(numberOfSides) sides." 238 } 239 } 240 241 class Square: NamedShape { 242 var sideLength: Double 243 244 init(sideLength: Double, name: String) { 245 self.sideLength = sideLength 246 super.init(name: name) 247 numberOfSides = 4 248 } 249 250 func area() -> Double { 251 return sideLength * sideLength 252 } 253 254 override func simpleDescription() -> String { 255 return "A square with sides of length \(sideLength)." 256 } 257 } 258 259 let test = Square(sideLength: 5.2, name: "my test square") 260 test.area() 261 test.simpleDescription() 262 263 class EquilateralTriangle: NamedShape { 264 var sideLenth: Double = 0.0 265 266 init(sideLength: Double, name: String) { 267 self.sideLenth = sideLength 268 super.init(name: name) 269 numberOfSides = 3 270 } 271 272 var perimeter: Double { 273 get { 274 return 3.0 * sideLenth 275 } 276 set { 277 sideLenth = newValue / 3.0 278 } 279 } 280 281 override func simpleDescription() -> String { 282 return "An equilateral triagle with side of length \(sideLenth)." 283 } 284 } 285 286 var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") 287 print(triangle.perimeter) 288 triangle.perimeter = 9.9 289 print(triangle.sideLenth) 290 291 class TriangleAndSquare { 292 var triangle: EquilateralTriangle { 293 willSet { 294 square.sideLength = newValue.sideLenth 295 } 296 } 297 298 var square:Square { 299 willSet { 300 triangle.sideLenth = newValue.sideLength 301 } 302 } 303 304 init(size: Double, name: String) { 305 square = Square(sideLength: size, name: name) 306 triangle = EquilateralTriangle(sideLength: size, name: name) 307 } 308 } 309 310 var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") 311 print(triangleAndSquare.square.sideLength) 312 print(triangleAndSquare.triangle.sideLenth) 313 triangleAndSquare.square = Square(sideLength:50, name: "larger square") 314 print(triangleAndSquare.triangle.sideLenth) 315 316 enum Rank: Int { 317 case Ace 318 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten 319 case Jack, Queen, King 320 321 func simpleDescription() -> String { 322 switch self { 323 case .Ace: 324 return "ace" 325 case .Jack: 326 return "jack" 327 case .Queen: 328 return "queen" 329 case .King: 330 return "king" 331 default: 332 return String(self.rawValue) 333 } 334 } 335 336 } 337 338 let ace = Rank.Ace 339 let aceRawValue = ace.rawValue 340 341 if let convertedRank = Rank(rawValue: 0) { 342 let threeDescription = convertedRank.simpleDescription() 343 } 344 345 enum Suit { 346 case Spades, Hearts, Diamonds, Clubs 347 348 func simpleDescription() -> String { 349 switch self { 350 case .Spades: 351 return "spades" 352 case .Hearts: 353 return "hearts" 354 case .Diamonds: 355 return "diamonds" 356 case .Clubs: 357 return "clubs" 358 } 359 } 360 361 } 362 363 let hearts = Suit.Hearts 364 let heartsDescription = hearts.simpleDescription() 365 366 enum ServerResponse { 367 case Result(String, String) 368 case Failure(String) 369 } 370 371 let success = ServerResponse.Result("6:00 am", "8:09 pm") 372 let failure = ServerResponse.Failure("Out of cheese.") 373 374 switch success { 375 case let .Result(sunrise, sunset): 376 let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." 377 case let .Failure(message): 378 print("Failure... \(message)") 379 } 380 381 struct Card { 382 var rank: Rank 383 var suit: Suit 384 func simpleDescription() -> String { 385 return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" 386 } 387 } 388 389 let threeOfSpades = Card(rank: .Three, suit: .Spades) 390 let threeOfSpadesDescription = threeOfSpades.simpleDescription() 391 392 protocol ExampleProtocol { 393 var simpleDescription: String { get } 394 mutating func adjust () 395 } 396 397 class SimpleClass: ExampleProtocol { 398 var simpleDescription: String = "A very simple class" 399 var anotherProperty: Int = 69105 400 func adjust() { 401 simpleDescription += "Now 100% adjusted." 402 } 403 } 404 405 var a = SimpleClass() 406 a.adjust() 407 let aDescription = a.simpleDescription 408 409 struct SimpleStructure: ExampleProtocol { 410 var simpleDescription: String = "A simple structure" 411 mutating func adjust() { 412 simpleDescription += "(adjusted)" 413 } 414 } 415 416 var b = SimpleStructure() 417 b.adjust() 418 let bDescription = b.simpleDescription 419 420 extension Int: ExampleProtocol { 421 var simpleDescription: String { 422 return "The number \(self)" 423 } 424 mutating func adjust() { 425 self += 42 426 } 427 } 428 429 print(7.simpleDescription) 430 let protocolValue: ExampleProtocol = a 431 print(protocolValue.simpleDescription) 432 433 enum PrinterError: Error { 434 case OutofPaper 435 case NoToner 436 case OnFire 437 } 438 439 func send(job: Int, toPrinter printerName:String) throws -> String { 440 if printerName == "Never Has Toner" { 441 throw PrinterError.OnFire 442 } 443 return "Job sent" 444 } 445 446 do { 447 let printerResponse = try send(job: 1040, toPrinter: "Never Has Toner") 448 print(printerResponse) 449 } catch { 450 print(error) 451 } 452 453 do { 454 let printerResponse = try send(job: 1440, toPrinter: "Never Has Toner") 455 print(printerResponse) 456 } catch PrinterError.OnFire { 457 print("I'll just put this over here, with rest of the fire.") 458 } catch let printerError as PrinterError { 459 print("Printer error: \(printerError).") 460 } catch { 461 print(error) 462 } 463 464 465 let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler") 466 let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner") 467 468 469 var fridgeIsOpen = false 470 let fridgeContent = ["milk", "eggs", "leftovers"] 471 472 func fridgecontains (_ food: String) -> Bool { 473 fridgeIsOpen = true 474 defer { 475 fridgeIsOpen = false 476 } 477 478 let result = fridgeContent.contains(food) 479 return result 480 } 481 482 fridgecontains("milk") 483 print(fridgeIsOpen) 484 485 func repeatItem<Item>(repeating item: Item, numberOfTimers: Int) -> [Item] { 486 var result = [Item]() 487 for _ in 0..<numberOfTimers { 488 result.append(item) 489 } 490 return result 491 } 492 repeatItem(repeating: "knock", numberOfTimers: 2) 493 494 enum OptionalValue<Wrapped> { 495 case None 496 case Some(Wrapped) 497 } 498 499 var possibleInteger: OptionalValue<Int> = .None 500 possibleInteger = .Some(100) 501 502 func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool 503 where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element { 504 for lhsItem in lhs { 505 for rhsItem in rhs { 506 if lhsItem == rhsItem { 507 return true 508 } 509 } 510 } 511 return false 512 } 513 514 anyCommonElements([1, 2, 3], [3])
怎么样成为程序员,学习和实践,日积月累...