I'm trying to learn protocols and associatedtypes. I have couple of protocols which declare associatedtypes, starting with:
protocol MasterViewModel {
associatedtype Item: AWMediaItem
...
}
AWMediaItem
is another protocol
protocol AWMediaItem {
var name: String { get }
var source: AWMediaSource { get }
}
And AWAlbum
is yet another protocol which inherits from AWMediaItem
protocol AWAlbum: AWMediaItem {
var albumName: String { get }
...
}
For some reason, in a class implementing MasterViewModel
protocol, I cannot set the AWAlbum to be the Item
.
final class AlbumsMasterViewModel: MasterViewModel {
typealias Item = AWAlbum // Error
...
}
The warning I get is
- Possibly intended match 'AlbumsMasterViewModel.Item' (aka 'AWAlbum') does not conform to 'AWMediaItem'
If I understand correctly, all AWAlbum's
will implement AWMediaItem
so why is this not working?
I think you meant to write
final class AlbumsMasterViewModel<Item: AWAlbum>: MasterViewModel {
}
I assume that when you write:
typealias Item = AWAlbum // Error
you want AlbumsMasterViewModel
's item to conform to your AWAlbum
protocol but you just create a typelias meaning that Item
is just an alias for AWAlbum
.
If you want to use a type alias you need a concrete type conforming to AWMediaItem
, not a protocol inheriting from it. eg:
class ConcreteAlbum: AWAlbum {
var albumName: String
var name: String
var source: AWMediaSource
...
}
final class AlbumsMasterViewModel: MasterViewModel {
typealias Item = ConcreteAlbum // No Error
}
if you want to use AlbumsMasterViewModel
with multiple Item
types you can also declare it that way:
final class AlbumsMasterViewModel<Item: AWMediaItem>: MasterViewModel {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.