Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring Protocol and Class in Swift Properties

Tags:

swift

ios8

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.

like image 867
lassej Avatar asked Jul 21 '14 06:07

lassej


1 Answers

There are actually two of ways to achieve this in Swift:

  1. 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?
    }
    
  2. 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
like image 136
akashivskyy Avatar answered Sep 23 '22 00:09

akashivskyy