Skip to content

Instantly share code, notes, and snippets.

@satoshin2071
Last active May 24, 2016 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satoshin2071/ddc5ee73c42dff783689b884997233c6 to your computer and use it in GitHub Desktop.
Save satoshin2071/ddc5ee73c42dff783689b884997233c6 to your computer and use it in GitHub Desktop.
Swift Pattern Matching, Part 2: tuples, ranges & types. Shakyo practice.
/*
From http://alisoftware.github.io/swift/pattern-matching/2016/03/30/pattern-matching-2/
Shakyo practice
Pattern Matching, Part 2: tuples, ranges & types
*/
import XCPlayground
import Foundation
import UIKit
// MARK: - tuples
let point = CGPoint(x:50, y:50)
switch (point.x, point.y) {
case (0,0): print("orgin")
case (0,_): print("x=0")
case (_,0): print("y=0")
case (let x, let y) where x==y: print("x==y")
default: print("default")
}
// MARK: - String & Chara
let car: Character = "J"
switch car {
case "A", "E", "I", "O", "U", "Y": print("Vowel")
default: print("Consonant")
}
// MARK: - Range
let count = 7
switch count {
case Int.min..<0: print("Negative!!")
case 0: print("0")
case 1: print("1")
case 2..<5: print("2..<5")
case 5..<10: print("5..<10")
default: print("10<")
}
func charType(car: Character) -> String {
switch car {
case "a", "e", "i", "o", "u":
return "Vowel"
case "A"..."Z", "a"..."z":
return "Consonant"
default:
return "Other"
}
}
print ("William Gibson".characters.map(charType))
// MARK: - Types
protocol Medium {
var title: String {get}
}
struct Book: Medium {
let title: String
let author: String
let publishYear: Int
}
struct Movie: Medium {
let title: String
let director: String
let year: Int
}
struct WebSite: Medium {
let title: String
let url: String
}
let media: [Medium] = [
Book(title: "neuromancer", author: "William Gibson", publishYear: 1984),
Movie(title: "Pacfic Rim", director: "Guillermo del Toro", year: 2013)
]
for medium in media {
switch medium {
case let book as Book:
print("\(book.title)")
case let movie as Movie:
print("\(movie.title)")
case let webSite as WebSite:
print("\(webSite.title)")
default:
print("default")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment