Skip to content

Instantly share code, notes, and snippets.

@ya-s-u
Last active January 4, 2018 00:53
Show Gist options
  • Save ya-s-u/900d60b759da651d109556a1062c0663 to your computer and use it in GitHub Desktop.
Save ya-s-u/900d60b759da651d109556a1062c0663 to your computer and use it in GitHub Desktop.
StoryboardInstantiatable
//: Playground - noun: a place where people can play
import UIKit
protocol ContextInjectable {
associatedtype Context = Void
func inject(_: Context)
}
extension ContextInjectable where Context == Void {
func inject(_ context: Context) {}
}
protocol Instantiatable: ContextInjectable {
init(with context: Context)
}
extension Instantiatable {
static func instantiate(with context: Context) -> Self {
return Self(with: context)
}
}
extension Instantiatable where Context == Void {
static func instantiate() -> Self {
return Self(with: ())
}
}
protocol StoryboardType {
static var storyboardName: String { get }
static var storyboardBundle: Bundle { get }
static var storyboard: UIStoryboard { get }
}
extension StoryboardType where Self: NSObjectProtocol {
static var storyboardBundle: Bundle {
return Bundle(for: self)
}
static var storyboard: UIStoryboard {
return UIStoryboard(name: storyboardName, bundle: storyboardBundle)
}
}
protocol StoryboardInstantiatable: Instantiatable, StoryboardType {}
extension StoryboardInstantiatable where Self: UIViewController {
init(with context: Context) {
let storyboard = (Self.self as StoryboardType.Type).storyboard
self = storyboard.instantiateInitialViewController() as! Self
self.inject(context)
}
}
class CustomViewController: UIViewController, StoryboardInstantiatable {
func inject(_ context: (header: String, items: [Int])) {
print(context.header)
}
static let storyboardName = ""
}
class CustomViewController2: UIViewController, StoryboardInstantiatable {
static let storyboardName = ""
}
//let custom = CustomViewController(with: (header: "aaa", items: []))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment