Skip to content

Instantly share code, notes, and snippets.

@alexcurylo
Last active May 17, 2016 02:45
Show Gist options
  • Select an option

  • Save alexcurylo/f648d8bee203dbe40f0acf27892c22f2 to your computer and use it in GitHub Desktop.

Select an option

Save alexcurylo/f648d8bee203dbe40f0acf27892c22f2 to your computer and use it in GitHub Desktop.

Revisions

  1. alexcurylo revised this gist May 17, 2016. No changes.
  2. alexcurylo revised this gist May 17, 2016. 1 changed file with 16 additions and 0 deletions.
    16 changes: 16 additions & 0 deletions PatternMatching.swift
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,19 @@
    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 {
  3. alexcurylo created this gist May 17, 2016.
    23 changes: 23 additions & 0 deletions PatternMatching.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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)")
    }