【问题标题】:Function to accept multiple struct types in Swift [duplicate]在Swift中接受多种结构类型的函数[重复]
【发布时间】:2016-05-31 22:45:12
【问题描述】:

我正在尝试将两个不同的结构(从同一协议继承)传递到一个结构 init 方法中,但出现以下错误:

Cannot convert value of type '[TopContentModel]' to '[TopModel]'

这是我的代码:

protocol TopModel {

}

struct TopContentModel: TopModel {
    var type: TableType?
    var contentType: ContentType?
    var title : String?
    var total: Float?
}

struct TopPlatformModel: TopModel {
    var platform: PlatformType?
    var total: Float?
    var type: TableType?
}

struct ChartInfo {
    var title: String?
    var type: ChartType?
    var prefix: String = ""
    var labels: [String]?
    var values: [Float]?
    var list: [TopModel]?
    var formatter: NSNumberFormatter?
    var special: String?
    var secondSpecial: String?
    var color: String?
}

var topEarningData = [TopContentModel]()

ChartInfo(title: "Top Earning Assets", type: .TopContent, prefix: "$", labels: nil, values: nil, list: topEarningData, formatter: nil, special: nil, secondSpecial: nil, color: "#37e0af")

【问题讨论】:

    标签: ios swift struct


    【解决方案1】:

    只需将topEarningData 声明为

    var topEarningData = [TopModel]()
    

    使其符合ChartInfo 中的规范。然后根据需要添加TopContentModelTopPlatformModel 的实例。

     36> var topEarningData = [TopModel]() 
    topEarningData: [TopModel] = 0 values
     37> topEarningData.append(TopContentModel())
     38> topEarningData.append(TopPlatformModel()) 
     39> topEarningData
    $R1: [TopModel] = 2 values {
      [0] = {
        type = nil
        contentType = nil
        title = nil
        total = nil
      }
      [1] = {
        platform = nil
        total = nil
        type = nil
      }
    }
     40> ChartInfo(title: "Top Earning Assets", type: nil, prefix: "$", labels: nil, values: nil, list: topEarningData, formatter: nil, special: nil, secondSpecial: nil, color: "#37e0af") 
    $R2: ChartInfo = {
      title = "Top Earning Assets"
      type = nil
      prefix = "$"
      labels = nil
      values = nil
      list = 2 values {
        [0] = {
          type = nil
          contentType = nil
          title = nil
          total = nil
        }
        [1] = {
          platform = nil
          total = nil
          type = nil
        }
      }
      formatter = nil
      special = nil
      secondSpecial = nil
      color = "#37e0af"
    }
     41>  
    

    【讨论】:

    • 成功了,谢谢!
    • 当您将数组提供给函数list: topEarningData as [TopModel]时,您也可以向下转换数组
    猜你喜欢
    • 2021-06-11
    • 2020-08-10
    • 2022-11-16
    • 1970-01-01
    • 2012-03-25
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    相关资源
    最近更新 更多