我正在generic function
中写一个protocol
,但是当error
中的overriding
function
时会出现inherited classes
。
我使用的第一种方式
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
}
}
但是这种方式会产生一个error
:
无法分配类型“ T”的值?键入“字符串?”
T
在overrided
类中是String
,但是compiler
不知道T
是String
第二种方式
protocol BaseCellProtocol {
func configure<T>(with object: T?)
}
class TableViewCell: BaseTableViewCell {
override func configure<String>(with object: String?) {
label.text = object
}
}
在这种情况下,error
是:
无法分配类型为'String'的值?键入“字符串?”
哇啊?
我是generics
的新手,我读过一些文献,但是对此有一些疑问。
更新
class BaseTableViewCell: UITableViewCell, BaseCellProtocol {
typealias T = String
func configure<T>(with object: T?) {
}
}
答案 0 :(得分:2)
只需删除功能中的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
}
}
。因为您在this.items = [
{label: 'Home', routerLink: '/'},
{label: 'Tab1', routerLink: '/tab1'},
{label: 'Tab2', routerLink: '/tab2', disabled= true},
{label: 'Tab3', routerLink: '/tab3'},
];
中有T。
if (this.auth.isUserLoggedIn) {
this.items[2].disabled = false
} else {
this.items[2].disabled = true
}