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
Question&Answers:
os