vivatus vivatus - 6 months ago 12
iOS Question

Function to accept multiple struct types in Swift

I'm trying to pass in two different structs (that inherit from the same protocol) into one struct init method but I'm getting the following error:

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


Here's the code that I have:

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")

Answer

Simply declare topEarningData as

var topEarningData = [TopModel]()

so that it meets the specification in ChartInfo. Then add instances of TopContentModel or TopPlatformModel as needed.

 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>