Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ryanmasondavies/2df1ed14821546eb92e04ce41e2bc0fa to your computer and use it in GitHub Desktop.
Save ryanmasondavies/2df1ed14821546eb92e04ce41e2bc0fa to your computer and use it in GitHub Desktop.
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
}
}
}
@ryanmasondavies
Copy link
Author

Would be improved by use of SwiftGen to generate enums for storyboard segues.

And also by SwiftGen/SwiftGen#19

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment