The Swift Programming Language Examples
源码在 GitHub:https://github.com/gewill/The-Swift-Programming-Language-2.1-Examples
Playground ->
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
import UIKit
enum VendingMachineError: ErrorType { case InvalidSelection case InsufficientFunds(coinsNeeded: Int) case OutOfStock }
struct Item { var price: Int var count: Int }
class VendingMachine { var inventory = [ "Candy Bar": Item(price: 12, count: 7), "Chips": Item(price: 10, count: 4), "Pretzels": Item(price: 7, count: 11) ] var coinsDeposited = 0 func dispenseSnack(snack: String) { print("Dispensing \(snack)") } func vend(itemNamed name: String) throws { guard var item = inventory[name] else { throw VendingMachineError.InvalidSelection } guard item.count > 0 else { throw VendingMachineError.OutOfStock } guard item.price <= coinsDeposited else { throw VendingMachineError.InsufficientFunds(coinsNeeded: item.price - coinsDeposited) } coinsDeposited -= item.price --item.count inventory[name] = item dispenseSnack(name) } }
let favoriteSnacks = [ "Alice": "Chips", "Bob": "Licorice", "Eve": "Pretzels", ] func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws { let snackName = favoriteSnacks[person] ?? "Candy Bar" try vendingMachine.vend(itemNamed: snackName) }
var vendingMachine = VendingMachine() vendingMachine.coinsDeposited = 8 do { try buyFavoriteSnack("Alice", vendingMachine: vendingMachine) } catch VendingMachineError.InvalidSelection { print("Invalid Selection.") } catch VendingMachineError.OutOfStock { print("Out of Stock.") } catch VendingMachineError.InsufficientFunds(let coinsNeeded) { print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.") }
func fetchData() -> Data? { if let data = try? fetchDataFromDisk() { return data } if let data = try? fetchDataFromServer() { return data } return nil }
let photo = try! loadImage("./Resources/John Appleseed.jpg")
func processFile(filename: String) throws { if exists(filename) { let file = open(filename) defer { close(file) } while let line = try file.readline() { } } }
|