Swift: Property conforming to a specific class and in the same time to multiple protocols

前端 未结 3 682
生来不讨喜
生来不讨喜 2020-12-05 04:22

In Objective-C, it\'s possible to write something like that:

@property(retain) UIView *myView;

But how can

3条回答
  •  长情又很酷
    2020-12-05 05:04

    One and probably a bit ugly one of the ways to do that, is to create a wrapper protocol for UIView:

    protocol UIViewRef {
        var instance: UIView { get }
    }
    

    Now it is possible to create a protocol which implements Protocol1, Protocol2 and UIViewRef, which is going to be used to get the UIView itself:

    protocol MyUIViewProtocol: UIViewRef, Protocol1, Protocol2 { }
    

    And last step will be implementing UIViewRef protocols for your UIViews, which, in you case, as I understand, already implement Protocol1 and Protocol2:

    // SomeOfMyViews already implements Protocol1 and Protocol2
    extension SomeOfMyUIViews: MyUIViewProtocol {
        var instance: UIView { return self }
    }
    

    As the result we have MyUIViewProtocol, implementers of which hold a reference to a UIView and each of them implement Protocol1 and Protocol2. One caveat though - to get the UIView itself, we need to ask it's reference from instance property. For example

    // Lets say we're somewhere in a UIViewController
    var views: [SomeOfMyUIView] = // Get list of my views
    views.forEach { self.view.addSubview($0.instance) }
    

提交回复
热议问题