In Objective-C you can require a class and additional protocol implementations for properties:
@property (nonatomic) UIViewController<UISplitViewDelegate> *viewController;
Is this possible in Swift? From the documentation it looks like you can only require either a class or a protocol.
There are actually two of ways to achieve this in Swift:
Using an empty "phantom" protocol. Create an empty protocol and make UIViewController
conform to it. This is the most "Swift" method, it's safe and it's dynamic (doesn't require specifying a class at compile-time).
protocol _UIViewControllerType {}
extension UIViewController: _UIViewControllerType {}
class MyClass {
weak var viewController: protocol<UISplitViewControllerDelegate, _UIViewControllerType>?
}
You can also declare a typealias
for this type (just to reduce the code mess).
class MyClass {
typealias ViewControllerType = protocol<UISplitViewControllerDelegate, _UIViewControllerType>
weak var viewController: ViewControllerType?
}
Using generic constraints. As mentioned by fnc12 and Konstantin Koval. This is safe, but doesn't allow you to "swap" the view controller instance at run-time.
class MyClass<T: UIViewController where T: UISplitViewControllerDelegate> {
weak var viewController: T?
}
I hope the next Swift release adds a way to specify both constraints without using a "phantom protocol"...
typealias ViewControllerType = UIViewController: UISplitViewControllerDelegate // wish
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With