gpt4 book ai didi

swift - 使用 Enum 和 Struct 进行静态和动态截面建模 - Swift 4

转载 作者:行者123 更新时间:2023-11-30 11:37:49 25 4
gpt4 key购买 nike

我有以下模型结构:

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]
}

问题是,枚举 Item 中的 case Pricing 实际上是一个数组。这是我从后端返回的数据:

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
}

如何在 viewDidLoadUITableViewDataSource 中将定价作为动态数组实现?

更新:

这是我的产品模型,我已删除其他字段:

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 个静态单元格,而第二部分中则有动态单元格。对这些数据进行建模的最佳方法是什么?我应该放弃上面的方法吗?

最佳答案

创建一个结构体来容纳 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
}

并通过使用关联值进行项目枚举来接受响应。

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 枚举与关联类型的一个很好的示例,因为它们是与大小写绑定(bind)的单独类型。

这还增加了更安全、更简洁的方式,可以在 tableView - collectionView 数据源中拥有更多单一类型的单元格。

关于swift - 使用 Enum 和 Struct 进行静态和动态截面建模 - Swift 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49557322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com