我陷入无法找到解决方案的境地。看到很多类似的问题,但无法解决。
所以我有一个View Controller,它显示两种类型的表视图列表
1)销售
2)购买
而且我决定为两者使用相同的View Controller
enum SalesRowType {
case salesOrderBooking
case salesInvoicing
case salesGrossContribution
}
enum PurchaseRowType {
case purchaseOrders
case amended_non_amended
case pending_grn_po
}
和
// BASE PROTOCOL
// ListRowType -> has title,image property
protocol HomeSubItemType:ListRowType {
associatedtype RowType
var type:RowType {get}
}
// PURCHASE ITEMS
struct PurchaseSubItem: HomeSubItemType {
typealias RowType = PurchaseRowType
var image: UIImage
var title: String
var type: PurchaseRowType
}
// SALES ITEMS
struct SalesSubItem : HomeSubItemType {
var image:UIImage
var title:String
var type:SalesRowType
}
在我的View Controller中,我想根据销售和购买创建数组
if let type = type {
switch type {
case .purchase:
self.title = "Purchase"
self.itemList = [
PurchaseSubItem(image: UIImage(named: "purchase-orders")!, title: "Purchase Orders", type: .purchaseOrders),
PurchaseSubItem(image: UIImage(named: "amended-non")!, title: "Amended/NON-Amended-UNAutho-PO", type: .purchaseOrders),
PurchaseSubItem(image: UIImage(named: "purchase-pending")!, title: "Pending GRN PO", type: .purchaseOrders)]
case .sales:
self.title = "Sales"
self.itemList =
[
SalesSubItem(image: UIImage(named: "sales-order-booking")!, title: "Sales Order Booking", type: .salesOrderBooking),
SalesSubItem(image: UIImage(named: "sales-invoice")!, title: "Sales Invoicing", type: .salesInvoicing),
SalesSubItem(image: UIImage(named: "sale-gross")!, title: "Sales Gross Contribution", type: .salesGrossContribution)]
default:
assertionFailure("Only Purchase and sales are handle here")
}
}
但是我不能声明数组
var itemList = [HomeSubItemType]()
//ERROR HERE
协议“ HomeSubItemType”只能用作一般约束,因为它具有“自我”或相关类型要求
请帮助我解决此问题。预先感谢
答案 0 :(得分:2)
更新
这是一个完全不同的解决方案,专注于解决问题而不是使用泛型
首先,我为枚举创建了一个协议,它是空的,因为它只是意味着将它们分组在一起
protocol RowType {}
两个枚举都实现了此功能,此处未显示,我将ListRowType修改为
protocol ListRowType {
var title: String {get}
var image: UIImage {get}
var type: RowType {get}
}
并完全跳过了HomeSubItemType
。
SubItem
现在是
struct SubItem: ListRowType {
var type: RowType
var title: String
var image: UIImage
}
和我的测试代码
var itemList = [ListRowType]()
let sale = SubItem(type: SalesRowType.salesInvoicing, title: "XYZ", image: UIImage())
itemList.append(sale)
let purchase = SubItem(type: PurchaseRowType.purchaseOrders, title: "ABC", image: UIImage())
itemList.append(purchase)
如果愿意,当然可以将其与原始PurchaseSubItem
和SalesSubItem
而非SubItem
一起使用
我用通用结构替换了这两个结构
struct SubItem<T>: HomeSubItemType {
typealias RowType = T
var type: T
var title: String
var image: UIImage
}
并像这样使用它
var itemList = [SubItem<SalesRowType>]()
var item = SubItem(type: SalesRowType.salesInvoicing, title: "XYZ", image: UIImage())
itemList.append(item)
因此,无论如何,您都需要最好的数组,如果出于某种原因,您必须只声明一个,然后声明它
var itemList = [Any]()