I’m trying to come up with an protocol-oriented MVVM for my tableviewcells. I have lots of them.
my viewModel
protocol PlainTableViewCellModelType {
var backgroundColor : UIColor {get}
var textColor: UIColor {get}
var titleFont : UIFont {get }
var accessoryType : UITableViewCellAccessoryType {get}
var textLabelNumberOfLines: Int {get}
}
my view
protocol PlainTableViewCellType{
associatedtype viewModel : PlainTableViewCellModelType
func setupUI(forViewModel viewModel: viewModel)
}
my class
conformance
class PlainTableViewCell : CCTableViewCell, PlainTableViewCellType{
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
func setupUI(forViewModel viewModel: PlainTableViewCellModelType){
contentView.backgroundColor = viewModel.backgroundColor
textLabel?.textColor = viewModel.textColor
textLabel?.font = viewModel.titleFont
accessoryType = viewModel.accessoryType
textLabel?.numberOfLines = viewModel.textLabelNumberOfLines
}
}
The current setups results in the following error:
Type 'PlainTableViewCell' does not conform to protocol 'PlainTableViewCellType'
I can get it to work if I do:
protocol PlainTableViewCellType{
func setupUI(forViewModel viewModel: PlainTableViewCellModelType)
}
But I want to have an associatedType
so I can enforce same model in all my PlainTableViewCellType
functions
EDIT: I'm happy to listen to alternatives, but first I want to know why this doesn't work.
associatedtype viewModel : PlainTableViewCellModelType
shouldn't it beassociatedtype viewModel = PlainTableViewCellModelType
? directly assigning the value of the associatedType. For the why, I believe that associatedType needs a value and you only did a dataType cast – ThenarviewModel
associated type cannot be satisfied byPlainTableViewCellModelType
, as that's not currently a type that conforms toPlainTableViewCellModelType
(see also https://mcmap.net/q/835705/-unable-to-use-protocol-as-associatedtype-in-another-protocol-in-swift/2976878 which is specific to associated types). – Phalansterian