Skip to content

Instantly share code, notes, and snippets.

@alexcurylo
Last active May 17, 2016 02:45
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 alexcurylo/f648d8bee203dbe40f0acf27892c22f2 to your computer and use it in GitHub Desktop.
Save alexcurylo/f648d8bee203dbe40f0acf27892c22f2 to your computer and use it in GitHub Desktop.
From Crunchy Development's Pattern Matching series
enum Media {
case Book(title: String, author: String, year: Int)
case Movie(title: String, director: String, year: Int)
case WebSite(urlString: String)
}
let mediaList: [Media] = [
.Book(title: "Harry Potter and the Philosopher's Stone", author: "J.K. Rowling", year: 1997),
.Movie(title: "Harry Potter and the Philosopher's Stone", director: "Chris Columbus", year: 2001),
.Book(title: "Harry Potter and the Chamber of Secrets", author: "J.K. Rowling", year: 1999),
.Movie(title: "Harry Potter and the Chamber of Secrets", director: "Chris Columbus", year: 2002),
.Book(title: "Harry Potter and the Prisoner of Azkaban", author: "J.K. Rowling", year: 1999),
.Movie(title: "Harry Potter and the Prisoner of Azkaban", director: "Alfonso Cuarón", year: 2004),
.WebSite(urlString: "https://en.wikipedia.org/wiki/List_of_Harry_Potter-related_topics")
]
extension Media {
var title: String? {
switch self {
case let .Book(title, _, _): return title
case let .Movie(title, _, _): return title
default: return nil
}
}
var kind: String {
// Remember part 1 where we bind all the associated values in one single anonymous tuple `_`?
switch self {
case .Book(_): return "Book"
case .Movie(_): return "Movie"
case .WebSite(_): return "Web Site"
}
}
}
print("All mediums with a title starting with 'Harry Potter'")
for case let (title?, kind) in mediaList.map({ ($0.title, $0.kind) })
where title.hasPrefix("Harry Potter") {
print(" - [\(kind)] \(title)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment