函数接受Swift中的多个结构类型

时间:2016-05-31 22:45:12

标签: ios swift struct

我试图将两个不同的结构(继承自相同的协议)传递到一个struct 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")

1 个答案:

答案 0 :(得分: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>