Last active
June 19, 2018 11:45
-
-
Save ryanmasondavies/2df1ed14821546eb92e04ce41e2bc0fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Book { | |
let title: String | |
} | |
protocol SegueHandling { | |
func handle(segue: UIStoryboardSegue) -> Bool | |
} | |
struct SegueHandler<ViewControllerType>: SegueHandling { | |
let identifier: String | |
let configure: (ViewControllerType, UIStoryboardSegue) -> Void | |
func handle(segue: UIStoryboardSegue) -> Bool { | |
guard identifier == segue.identifier else { | |
return false | |
} | |
guard let viewController = segue.destination as? ViewControllerType else { | |
return false | |
} | |
configure(viewController, segue) | |
return true | |
} | |
} | |
class ViewController: UITableViewController { | |
let books = [ | |
Book(title: "My Norwegian Adventure"), | |
Book(title: "A Guide to Buying a House"), | |
] | |
private var segueHandlers: [SegueHandling] = [] | |
func performSegue<ViewControllerType>(withIdentifier identifier: String, configure: @escaping (ViewControllerType, UIStoryboardSegue) -> Void) { | |
segueHandlers.append(SegueHandler<ViewControllerType>(identifier: identifier, configure: configure)) | |
performSegue(withIdentifier: identifier, sender: self) | |
} | |
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { | |
guard let index = segueHandlers.index(where: { $0.handle(segue: segue) }) else { | |
return | |
} | |
segueHandlers.remove(at: index) | |
} | |
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return books.count | |
} | |
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let book = books[indexPath.row] | |
let cell = tableView.dequeueReusableCell(withIdentifier: "Book", for: indexPath) | |
cell.textLabel?.text = book.title | |
return cell | |
} | |
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { | |
let book = books[indexPath.row] | |
performSegue(withIdentifier: "showDetail") { (viewController: BookViewController, segue: UIStoryboardSegue) in | |
viewController.book = book | |
} | |
} | |
} | |
class BookViewController: UIViewController { | |
var book: Book? { | |
didSet { | |
title = book?.title | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be improved by use of SwiftGen to generate enums for storyboard segues.
And also by SwiftGen/SwiftGen#19