Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a Swift typealias for any object that implements multiple protocols

I'm trying to define a typealias for a UITableViewCell's delegate property that conforms to multiple protocols. This is what I'm trying to do and Swift complains that my syntax is wrong:

// The typealias definition typealias CellDelegate = AnyObject<UIPickerViewDataSource, UIPickerViewDelegate>  // In my UITableViewCell subclass: weak var delegate: CellDelegate? 

"Cannot specialize the non-generic type AnyObject" is the error I'm getting. How do I do this correctly?

like image 381
MLQ Avatar asked Apr 18 '15 08:04

MLQ


People also ask

How do I declare Typealias in Swift?

Declaring a typealias A typealias can be declared in Swift using the typealias keyword followed by the type you want to assign. A very simple example to understand how they can be used is by making an alias for currency, like Dollars.

What is Typealias in Swift?

A type alias allows you to provide a new name for an existing data type into your program. After a type alias is declared, the aliased name can be used instead of the existing type throughout the program. Type alias do not create new types. They simply provide a new name to an existing type.

What is protocol composition Swift?

Protocol composition is the process of combining multiple protocols into a single protocol. You can think of it as multiple inheritance. With protocol DoSomething , below, class HasSomethingToDo is able to do whatShouldBeDone and anotherThingToBeDone .


2 Answers

The code that you posted has a different meaning from what you'd expect. You're treating AnyObject like a generic type, with UIPickerViewDataSource and UIPickerViewDelegate as type arguments. It's the same thing as creating a Dictionary with Int keys and String values, for example:

var someDictionary: Dictionary<Int, String> 

What you're trying to accomplish needs a different construct, called protocol composition. Swift provides it specifically to express types that conforms to multiple protocols. Its syntax is the following, you can use it anywhere you can use regular types:

FirstProtocol & SecondProtocol 

Using this feature, your code would become:

// The typealias definition typealias CellDelegate = UIPickerViewDataSource & UIPickerViewDelegate  // In my UITableViewCell subclass: weak var delegate: CellDelegate? 

Protocol composition is explained in Apple's guide to the Swift language, here.

EDIT: Updated to Swift 3 syntax, thanks @raginmari

like image 95
EliaCereda Avatar answered Sep 25 '22 18:09

EliaCereda


if you want to declare multiprotocol:

protocol<A, B> 
like image 45
dimpiax Avatar answered Sep 24 '22 18:09

dimpiax