【问题标题】:Multiple types in function多种功能类型
【发布时间】:2020-08-03 21:04:57
【问题描述】:

我想将T 类型传递给函数(例如,它包含RatingCell),但我不明白如何使T 类型完全定义为RatingCell

func configureQuestionCell<T>(cellType: T, question: Question, answers: [String]?) -> UITableViewCell {

        let cell = self.blockContent.dequeueReusableCell(withIdentifier: ReusableCellID.pickerCell.rawValue) as! T
        //Value of type 'T' has no member ... 
        cell.delegate = self 
        cell.questionId = question.questionId
        cell.cellTitle.text = question.title
        cell.answerVariants = question.answerVariants 
        if answers != nil { 
            cell.userAnswers = answers!
        }
        return cell
    }

我在评论中添加错误。我也确定RatingCell 包含所有这些参数

【问题讨论】:

标签: swift function class types


【解决方案1】:

一种可能的解决方案是添加协议

protocol Reusable {
    var delegate : ReusableDelegate { get set } // change the type to the real delegate type
}

并将泛型类型约束到协议。无论如何,您都应该将泛型类型限制为UITableViewCell

func configureQuestionCell<T>(cellType: T) where T : UITableViewCell & Reusable {
    let cell = self.blockContent.dequeueReusableCell(withIdentifier: ReusableCellID.ratingCell.rawValue) as! T
    cell.delegate = self
}

对于多个不同的委托类型,使用关联类型

protocol Reusable {
    associatedtype DelegateType
    var delegate : DelegateType { get set } 
}

并在单元格中采用协议并添加

typealias DelegateType = < The actual delegate type of the cell >

【讨论】:

  • 如何使用它?我需要使用哪个代表?
  • 单元格的自定义委托类型。
  • 如果一个有 6-7 种细胞类型我需要做什么?你能给我举个例子吗?
  • 为了清楚起见,我编辑为。目前还没有决定如何指定 T 显式类型
  • 泛型的目标是T 不明确。
【解决方案2】:

我不是 Swift 的专业人士,但是,您是否尝试将接口作为参数传递,所以所有的“T”都应该有 .delegate 像这样应该可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    相关资源
    最近更新 更多