我有以下模型结构:
enum ProductSectionType {
case ProductDetails
case ProductPricing
}
enum Item {
case Brand
case Collection
case Dimensions
case SoldBy
case Category
case Pricing
}
struct ProductSection {
var type: ProductSectionType
var items: [Item]
}问题是,enum项目中的案例定价实际上是一个数组。这是我从后端返回的数据:
Product(productCode: "SomeCode",
productBrand: "SomeBrand",
productCategory: "SomeCategory",
productDimensions: "SomeDimensions",
productCollection: "Some Collection",
productSoldBy: "??",
productPricing: ["X-Price = 100", "Y-Price = 200"]))在我的viewDidLoad中有:
sections =
[ProductSection(type: .ProductDetails,
items: [.Brand, .Collection, .Category, .Dimensions, .SoldBy]),
ProductSection(type: .ProductPricing,
items: [.Pricing])]在我的UITableViewDataSource中有:
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].items.count
}如何在viewDidLoad & UITableViewDataSource中实现动态数组的定价
更新:
下面是我的产品模型,我移除了其他字段:
struct Product {
let productPricing: [String]
etc.......
var dictionary: [String : Any] {
return [
etc.......
"Pricing": productPricing
]
}
}
extension Product: DocumentSerializable {
init?(dictionary: [String : Any]) {
guard let productCode = dictionary["Code"] as? String,
etc......
let productPricing = dictionary["Pricing"] as? [String]
else { return nil }
self.init(productCode: productCode,
etc......
productPricing: productPricing)
}
}我只是在一个部分中有5个静态单元格,在第二个部分中有一个动态单元格。对数据建模的最佳方法是哪一种?我应该放弃上面的方法吗?
发布于 2018-03-29 17:43:47
创建一个结构以适应api响应。
struct Product: Codable {
var productCode: String
var productCategory: String
...
var productPrice: [String] // or a other struct if only x and y prices are there.
var productPrice: PPrice
}
struct PPrice {
var XPrice: String
var YPrice: String
}并通过使用associated value进行Item枚举来接受响应。
enum Item {
case Brand(String)
case Collection(String)
...
case Pricing([String]) or Pricing(PPrice) // in case of only x and y
}现在是各节
extension Product {
var detailsItems: [Item] {
return [.Brand(self.productBrand),
.Collection(self.productCollection),...]
}
var priceItems: [Item] {
return self.productPrice.map{.Price($0)}
or
return [.Price(self.productPrice.XPrice),
.Price(self.productPrice.YPrice)]
}
}这是一个有关联类型的Swift枚举的一个很好的例子,因为它们是与大小写绑定的单个类型。
这也增加了在tableView - collectionView数据源中拥有比单一类型单元更安全和更干净的方式。
https://stackoverflow.com/questions/49557322
复制相似问题