Mobile/iOS
swift. Type matching - 2. Type별
out of coding
2019. 3. 23. 19:37
Type matching의 두번째입니다.
각 데이터 타입별로 값을 비교하는 방법입니다.
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 | // Tuples let point = CGPoint(x: 7, y: 0) switch (point.x, point.y) { case (0,0): print("On the origin!") case (0,_): print("x=0: on Y-axis!") case (_,0): print("y=0: on X-axis!") case (let x, let y) where x == y: print("On y=x") default: print("Quite a random point here.") } // Char, String의 경우 let char: Character = "J" switch char { case "A", "E", "I", "O", "U", "Y": print("Vowel") default: print("Consonant") } let str = "A" switch str { case "A", "E", "I", "O", "U", "Y": print("Vowel") default: print("Consonant") } // Ranges let count = 7 switch count { case Int.min..<0: print("Negative count, really?") case 0: print("Nothing") case 1: print("One") case 2..<5: print("A few") case 5..<10: print("Some") default: print("Many") } // lamda의 function 대입 func charType(_ car: Character) -> String { switch car { case "A", "E", "I", "O", "U", "Y", "a", "e", "i", "o", "u", "y": return "Vowel" case "A"..."Z", "a"..."z": return "Consonant" default: return "Other" } } print("Jules Verne".characters.map(charType)) // ["Consonant", "Vowel", "Consonant", "Vowel", "Consonant", "Other", "Consonant", "Vowel", "Consonant", "Consonant", "Vowel"] // Array의 protocol type을 protocol Titleable { var title: String { get } } struct Book: Titleable { let title: String let author: String let year: Int } struct Movie: Titleable { let title: String let director: String let year: Int } struct WebSite: Titleable { let url: NSURL let title: String } // And an array of Media to switch onto let media: [Titleable] = [ Book(title: "20,000 leagues under the sea", author: "Jules Verne", year: 1870), Movie(title: "20,000 leagues under the sea", director: "Richard Fleischer", year: 1955) ] for element in media { switch element { case let book as Book: print("book = \(book)") case let movie as Movie: print("movie = \(movie)") case is WebSite: print("website") default: print("element = \(element)") } } | cs |