How do I declare a variable that has a type and implements a protocol?

后端 未结 3 743
太阳男子
太阳男子 2020-11-28 10:55

My app has a protocol for detail view controllers, stating they must have a viewModel property:

protocol DetailViewController: class {
    var v         


        
3条回答
  •  眼角桃花
    2020-11-28 11:42

    As of Swift 4, you can now do this.

    Swift 4 implemented SE-0156 (Class and Subtype existentials).

    The equivalent of this Objective-C syntax:

    @property (strong, nonatomic) UIViewController * detailViewController;
    

    Now looks like this in Swift 4:

    var detailViewController: UIViewController & DetailViewController
    

    Essentially you get to define one class that the variable conforms to, and N number of protocols it implements. See the linked document for more detailed information.

提交回复
热议问题