【发布时间】:2020-08-11 16:54:00
【问题描述】:
我希望从多个来源(Web REST 调用)检索两个数组数据结构数组,并将它们转换为一个可以在 UITableView 上使用的单一结构数组。
我最初走的是创建多维数组的道路,但当我不得不将类型向下转换为 [AnyObject] 并且无法读取属性时,这证明很困难。
示例数据:-
import UIKit
// First Set Of Data
struct Items : Codable{
// List of 'items'
let items : [Item]
}
struct Item: Codable{
// Items inside the array
let id : String
let name : String
let price : String
let imageURL : String
let weight : String
}
// ******** SECOND SET OF DATA
struct SecondSetOfItems : Codable {
let mainFopCollection : MainFopCollection?
}
struct MainFopCollection : Codable {
let sections : [Sections]?
}
struct Sections : Codable {
let id : String?
let fops : [Fops]?
}
struct Fops : Codable {
let sku : String?
let hash : Int?
let product : Product?
}
struct Product : Codable {
let sku : String?
let name : String?
let price : Price?
}
struct Price : Codable {
let current : Double?
let lpp : Bool?
let unit : Unit?
let type : String?
}
struct finalSetOfItems{
let name : String?
let price: String?
}
var array1 = [Items]()
var array2 = [SecondSetOfItems]()
// Originally tried:-
var multiArray = [[AnyObject]]()
multiArray.append(array1 as [AnyObject])
multiArray.append(array2 as [AnyObject])
// This part errors because I can't access this property
let name = multiArray[1][1].name
// Also tried a ternary operator (this part is within cellforrowat in my UITableViewController but I want the data to be dynamic, and not hard coded.
let name = indexPath.section == 0 ? array1![indexPath.row].name : array2![0].sections![0].fops![indexPath.row].product!.name
但后来我无法访问数组的属性,因为名称太模糊,而且由于我使用多种数据类型,因此很难明确我要查找的内容。
第二组数据比第一组更复杂(也更深入)。
所需的输出:-
// Take complex array1 and array2 and change them into a type of finalSetOfItems
var array1 = [Items]()
var array2 = [SecondSetOfItems]()
var arrayOutput = [finalSetOfItems]()
有没有办法可以将两组数据转换为单一结构类型,以便更容易访问属性? 最终目标是将每个数组转换为 UITableView 中自己的部分,以表示数据的来源
抱歉,如果我的问题措辞不当,我对 Swift 还是比较陌生。任何帮助将不胜感激
【问题讨论】: