枚举和结构体:
1 // 2 // ViewController3.swift 3 // SwiftBasicDemo 4 // 5 // Created by 思 彭 on 16/11/16. 6 // Copyright © 2016年 思 彭. All rights reserved. 7 8 // 枚举和结构体 9 10 import UIKit 11 12 class ViewController3: UIViewController { 13 14 override func viewDidLoad() { 15 super.viewDidLoad() 16 self.title = "枚举和结构体" 17 // 1. 枚举的使用 18 let ace = Rank.ace 19 print(ace) // ace 20 let acrRawValue = ace.rawValue 21 print(acrRawValue) // 1 22 23 if let convertedRank = Rank(rawValue: 3) { 24 25 let threeDescription = convertedRank.simpleDescription() 26 print(threeDescription) // 3 27 } 28 29 // 2. 30 let hearts = Suit.hearts 31 let heartedDescription = hearts.simpleDescription() 32 print("heartedDescription = (heartedDescription)") 33 34 // 3. 35 let success = ServerResponse.result("6:00 am", "8:09 pm") 36 let failure = ServerResponse.failure("Out of cheese.") 37 38 switch success { 39 case let .result(sunrise, sunset): 40 print("Sunrise is at (sunrise) and sunset is at (sunset).") 41 case let .failure(message): 42 print("Failure... (message)") 43 44 } 45 // 4.结构体 46 let structVar = Card(rank: .ace, suit: .hearts) 47 print(structVar.simpleDescription()) 48 49 } 50 51 // 定义枚举 52 enum Rank: Int { 53 case ace = 1 54 case two, three, four,five, six, seven, eight, nine, ten 55 case jack, queen, king 56 func simpleDescription() -> String { 57 58 switch self { 59 60 case .ace: 61 return "ace" 62 case .jack: 63 return "jack" 64 case .queen: 65 return "queen" 66 case .king: 67 return "king" 68 default: 69 return String(self.rawValue) 70 } 71 } 72 } 73 // 定义枚举 74 enum Suit { 75 case spades, hearts, diamonds, clubs 76 func simpleDescription() -> String { 77 switch self { 78 case .spades: 79 return "spades" 80 case .hearts: 81 return "hearts" 82 case .diamonds: 83 return "diamonds" 84 case .clubs: 85 return "clubs" 86 } 87 } 88 } 89 90 // 定义枚举元组 91 enum ServerResponse { 92 case result(String, String) 93 case failure(String) 94 } 95 96 // 定义结构体 97 struct Card { 98 var rank: Rank 99 var suit: Suit 100 func simpleDescription() -> String { 101 102 return "The (rank.simpleDescription()) of (suit.simpleDescription())" 103 } 104 } 105 }