Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift associated types and protocol inheritance

I'm using Swift 2.2 and I declared a protocol with associated type as follow:

protocol CollectionViewModeling {
    associatedtype CellType
    func cellAtIndexPath(indexPath: NSIndexPath) -> CellType
}

Now I have a view model protocol conform to the above protocol :

enum MyItemCell {
    case MyItemCell1, MyItemCell2
}
protocol ItemsListViewModeling: CollectionViewModeling {
    associatedtype CellType = MyCell
}

Finally, somewhere else, I want to declare a var that is conform to le protocol ItemsListViewModeling :

var viewModel: ItemsListViewModeling

And I'm getting this error :

Protocol 'ItemsListViewModeling' can only be used as a generic constraint because it has Self or associated type requirements

But I can easily create a class that implements this protocol.

Is it possible to declare a var to an associated typed protocol ? As I'm giving the final type of the associated type in the protocol ItemsListViewModeling, I don't understand why am I seeing this error from the compiler.

Thanks

like image 443
Antonin Avatar asked Apr 06 '16 13:04

Antonin


1 Answers

See there stackoverflow.com

You can't treat protocols with associated types like regular protocols and declare them as standalone variable types.

like image 128
Tikhonov Aleksandr Avatar answered Sep 21 '22 05:09

Tikhonov Aleksandr