Reputation: 92
I am writing a generic function
in a protocol
, but an error
occurs when overriding
this function
in inherited classes
.
The first way i use
protocol BaseCellProtocol {
associatedtype T
func configure<T>(with object: T?)
}
class TableViewCell: BaseTableViewCell {
typealias T = String
override func configure<T>(with object: T?) {
label.text = object as? T
}
}
But this way produce an error
:
Cannot assign value of type 'T?' to type 'String?'
T
was overrided
in class as String
, but compiler
don't understand that T
is String
The second way
protocol BaseCellProtocol {
func configure<T>(with object: T?)
}
class TableViewCell: BaseTableViewCell {
override func configure<String>(with object: String?) {
label.text = object
}
}
In this case, the error
is:
Cannot assign value of type 'String?' to type 'String?'
Whaaaaat?
I am new to generics
, I read some literature, but I have some problems with this.
update
class BaseTableViewCell: UITableViewCell, BaseCellProtocol {
typealias T = String
func configure<T>(with object: T?) {
}
}
Upvotes: 4
Views: 68
Reputation: 1739
Just remove <T>
in function. Because you have T in typealias
.
protocol BaseCellProtocol {
associatedtype T
func configure(with object: T?)
}
class BaseTableViewCell: UITableViewCell, BaseCellProtocol {
typealias T = String
func configure(with object: T?) {
}
}
class TableViewCell: BaseTableViewCell {
override func configure(with object: String?) {
label.text = object
}
}
Upvotes: 2