In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?

旧城冷巷雨未停 提交于 2019-12-17 02:14:07

问题


In Swift I can explicitly set the type of a variable by declaring it as follows:

var object: TYPE_NAME

If we want to take it a step further and declare a variable that conforms to multiple protocols we can use the protocol declarative:

var object: protocol<ProtocolOne,ProtocolTwo>//etc

What if I would like to declare an object that conforms to one or more protocols and is also of a specific base class type? The Objective-C equivalent would look like this:

NSSomething<ABCProtocolOne,ABCProtocolTwo> * object = ...;

In Swift I would expect it to look like this:

var object: TYPE_NAME,ProtocolOne//etc

This gives us the flexibility of being able to deal with the implementation of the base type as well as the added interface defined in the protocol.

Is there another more obvious way that I might be missing?

Example

As an example, say I have a UITableViewCell factory that is responsible for returning cells conforming to a protocol. We can easily setup a generic function that returns cells conforming to a protocol:

class CellFactory {
    class func createCellForItem<T: UITableViewCell where T:MyProtocol >(item: SpecialItem,tableView: UITableView) -> T {
        //etc
    }
}

later on I want to dequeue these cells whilst leveraging both the type and the protocol

var cell: MyProtocol = CellFactory.createCellForItem(somethingAtIndexPath) as UITableViewCell

This returns an error because a table view cell does not conform to the protocol...

I would like to be able to specify that cell is a UITableViewCell and conforms to the MyProtocol in the variable declaration?

Justification

If you are familiar with the Factory Pattern this would make sense in the context of being able to return objects of a particular class that implement a certain interface.

Just like in my example, sometimes we like to define interfaces that make sense when applied to a particular object. My example of the table view cell is one such justification.

Whilst the supplied type does not exactly conform to the mentioned interface, the object the factory returns does and so I would like the flexibility in interacting with both the base class type and the declared protocol interface


回答1:


In Swift 4 it is now possible to declare a variable that is a subclass of a type and implements one or more protocols at the same time.

var myVariable: MyClass & MyProtocol & MySecondProtocol

or as the parameter of a method:

func shakeEm(controls: [UIControl & Shakeable]) {}

Apple announced this at WWDC 2017 in Session 402: Whats new in Swift

Second, I want to talk about composing classes and protocols. So, here I've introduced this shakable protocol for a UI element that can give a little shake effect to draw attention to itself. And I've gone ahead and extended some of the UIKit classes to actually provide this shake functionality. And now I want to write something that seems simple. I just want to write a function that takes a bunch of controls that are shakable and shakes the ones that are enabled to draw attention to them. What type can I write here in this array? It's actually frustrating and tricky. So, I could try to use a UI control. But not all UI controls are shakable in this game. I could try shakable, but not all shakables are UI controls. And there's actually no good way to represent this in Swift 3. Swift 4 introduces the notion of composing a class with any number of protocols.




回答2:


You cannot declare variable like

var object:Base,protocol<ProtocolOne,ProtocolTwo> = ...

nor declare function return type like

func someFunc() -> Base,protocol<MyProtocol,Protocol2> { ... }

You can declare as a function parameter like this, but it's basically up-casting.

func someFunc<T:Base where T:protocol<MyProtocol1,MyProtocol2>>(val:T) {
    // here, `val` is guaranteed to be `Base` and conforms `MyProtocol` and `MyProtocol2`
}

class SubClass:BaseClass, MyProtocol1, MyProtocol2 {
   //...
}

let val = SubClass()
someFunc(val)

As of now, all you can do is like:

class CellFactory {
    class func createCellForItem(item: SpecialItem) -> UITableViewCell {
        return ... // any UITableViewCell subclass
    }
}

let cell = CellFactory.createCellForItem(special)
if let asProtocol = cell as? protocol<MyProtocol1,MyProtocol2> {
    asProtocol.protocolMethod()
    cell.cellMethod()
}

With this, technically cell is identical to asProtocol.

But, as for compiler, cell has interface of UITableViewCell only, while asProtocol has only protocols interface. So, when you want to call UITableViewCell's methods, you have to use cell variable. When you want to call protocols method, use asProtocol variable.

If you are sure that cell conforms to protocols you don't have to use if let ... as? ... {}. like:

let cell = CellFactory.createCellForItem(special)
let asProtocol = cell as protocol<MyProtocol1,MyProtocol2>



回答3:


Unfortunately, Swift does not support object level protocol conformance. However, there is a somewhat awkward work-around that may serve your purposes.

struct VCWithSomeProtocol {
    let protocol: SomeProtocol
    let viewController: UIViewController

    init<T: UIViewController>(vc: T) where T: SomeProtocol {
        self.protocol = vc
        self.viewController = vc
    }
}

Then, anywhere you need to do anything that UIViewController has, you would access the .viewController aspect of the struct and anything you need the protocol aspect, you would reference the .protocol.

For Instance:

class SomeClass {
   let mySpecialViewController: VCWithSomeProtocol

   init<T: UIViewController>(injectedViewController: T) where T: SomeProtocol {
       self.mySpecialViewController = VCWithSomeProtocol(vc: injectedViewController)
   }
}

Now anytime you need mySpecialViewController to do anything UIViewController related, you just reference mySpecialViewController.viewController and whenever you need it to do some protocol function, you reference mySpecialViewController.protocol.

Hopefully Swift 4 will allow us to declare an object with protocols attached to it in the future. But for now, this works.

Hope this helps!




回答4:


EDIT: I was mistaken, but if somebody else read this misunderstanding like me, I leave this answer out there. The OP asked about checking for protocol conformance of the object of a given subclass, and that is another story as the accepted answer shows. This answer talks about protocol conformance for the base class.

Maybe I'm mistaken, but are you not talking about adding protocol conformance to the UITableCellView class? The protocol is in that case extended to the base class, and not the object. See Apple's documentation on Declaring Protocol Adoption with an Extension which in your case would be something like:

extension UITableCellView : ProtocolOne {}

// Or alternatively if you need to add a method, protocolMethod()
extension UITableCellView : ProcotolTwo {
   func protocolTwoMethod() -> String {
     return "Compliant method"
   }
}

In addition to the already referenced Swift documentation, also see Nate Cooks article Generic functions for incompatible types with further examples.

This gives us the flexibility of being able to deal with the implementation of the base type as well as the added interface defined in the protocol.

Is there another more obvious way that I might be missing?

Protocol Adoption will do just this, make an object adhere to the given protocol. Be however aware of the adverse side, that a variable of a given protocol type does not know anything outside of the protocol. But this can be circumvented by defining a protocol which has all the needed methods/variables/...

Whilst the supplied type does not exactly conform to the mentioned interface, the object the factory returns does and so I would like the flexibility in interacting with both the base class type and the declared protocol interface

If you would like for a generic method, variable to conform to both a protocol and base class types, you could be out of luck. But it sounds like you need to define the protocol wide enough to have the needed conformance methods, and at the same time narrow enough to have the option to adopt it to base classes without too much work (i.e. just declaring that a class conforms to the protocol).




回答5:


I once had a similar situation when trying to link my generic interactor connections in Storyboards (IB won't allow you to connect outlets to protocols, only object instances), which I got around by simply masking the base class public ivar with a private computed property. While this does not prevent someone from making illegal assignments per se, it does provide a convenient way to safely prevent any unwanted interaction with a non-conforming instance at runtime. (i.e. prevent calling delegate methods to objects that don't conform to the protocol.)

Example:

@objc protocol SomeInteractorInputProtocol {
    func getSomeString()
}

@objc protocol SomeInteractorOutputProtocol {
    optional func receiveSomeString(value:String)
}

@objc class SomeInteractor: NSObject, SomeInteractorInputProtocol {

    @IBOutlet var outputReceiver : AnyObject? = nil

    private var protocolOutputReceiver : SomeInteractorOutputProtocol? {
        get { return self.outputReceiver as? SomeInteractorOutputProtocol }
    }

    func getSomeString() {
        let aString = "This is some string."
        self.protocolOutputReceiver?.receiveSomeString?(aString)
    }
}

The "outputReceiver" is declared optional, as is the private "protocolOutputReceiver". By always accessing the outputReceiver (a.k.a. delegate) through the latter (the computed property), I effectively filter out any objects that do not conform to the protocol. Now I can simply use optional chaining to safely call out to the delegate object whether or not it implements the protocol or even exists.

To apply this to your situation, you can have the public ivar be of type "YourBaseClass?" (as opposed to AnyObject), and use the private computed property to enforce the protocol conformance. FWIW.



来源:https://stackoverflow.com/questions/26401778/in-swift-how-can-i-declare-a-variable-of-a-specific-type-that-conforms-to-one-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!