Skip to content

Instantly share code, notes, and snippets.

@nanoxd
Created October 16, 2018 14:14
Show Gist options
  • Save nanoxd/e52c83e435ad96717652b704a23ce6af to your computer and use it in GitHub Desktop.
Save nanoxd/e52c83e435ad96717652b704a23ce6af to your computer and use it in GitHub Desktop.
[HasCustomView] Define a custom property for `UIViewController` to use a typed view #swift #ios
/// The HasCustomView protocol defines a customView property for UIViewControllers to be used in exchange of the regular view property.
/// In order for this to work, you have to provide a custom view to your UIViewController at the loadView() method.
public protocol HasCustomView {
associatedtype CustomView: UIView
}
extension HasCustomView where Self: UIViewController {
/// The custom typed view
public var customView: CustomView {
guard let customView = view as? CustomView else {
fatalError("Expected view to be of type \(CustomView.self) but got \(type(of: view)) instead")
}
return customView
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment