【问题标题】:Overriding a generic function produce an error覆盖泛型函数会产生错误
【发布时间】:2019-09-01 13:22:42
【问题描述】:

我在protocol 中写了一个generic function,但是当overriding 这个functioninherited classes 中出现error

我使用的第一种方式

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 在课堂上是overridedString,但compiler 不明白TString

第二种方式

protocol BaseCellProtocol {
    func configure<T>(with object: T?)
}

class TableViewCell: BaseTableViewCell {

    override func configure<String>(with object: String?) {
        label.text = object
    }

}

在这种情况下,error 是:

无法分配“字符串”类型的值?键入“字符串?”

什么?

我是generics 的新手,我阅读了一些文献,但对此我有一些问题。

更新

class BaseTableViewCell: UITableViewCell, BaseCellProtocol {

    typealias T = String

    func configure<T>(with object: T?) {
    }

}

【问题讨论】:

  • 代码无法编译
  • 那么,BaseTableViewCell 符合 BaseCellProtocol 吗?
  • @MayRestinPeace,是的
  • @idev.agg.mf 您在BaseTableViewCell 中给出的类型别名是什么?你能把BaseTableViewCell的代码贴出来吗?
  • 你不需要将函数定义为泛型,在协议中尝试func configure(with object: T?)

标签: swift xcode generics


【解决方案1】:

只需删除函数中的&lt;T&gt;。因为typealias 中有 T。

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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2019-01-30
    相关资源
    最近更新 更多