我试图用一系列元素填充UITableView。这些元素是结构:
public enum itemNumber {
case Item1
case Item2
case Item3
case Item4
case Item5
case Item6
}
public enum sectionNumber {
case Section1
case Section2
case Section3
case Section4
}
public struct Item {
var itemNumber: itemNumber?
var sectionNumber: sectionNumber?
var checkmark: Bool
init(sectionNumber: Int, itemNumber: Int, checkmark: Bool) {
switch sectionNumber {
case 0: self.sectionNumber = .Section1
case 1: self.sectionNumber = .Section2
case 2: self.sectionNumber = .Section3
case 3: self.sectionNumber = .Section4
default: break
}
switch itemNumber {
case 0: self.itemNumber = .Item1
case 1: self.itemNumber = .Item2
case 2: self.itemNumber = .Item3
case 3: self.itemNumber = .Item4
case 4: self.itemNumber = .Item5
case 5: self.itemNumber = .Item6
default: break
}
self.checkmark = checkmark
}
}
在我的Controller类中,我想检查每个Item
的节号,以便将其分配到正确的部分:
func getNumOfItemsPerSection(section: Int) -> Int {
var num = 0
switch section {
case 0: num = self.items.filter { $0.sectionNumber == .Section1 }.count
case 1: num = self.items.filter { $0.sectionNumber == .Section2 }.count
case 2: num = self.items.filter { $0.sectionNumber == .Section3 }.count
case 3: num = self.items.filter { $0.sectionNumber == .Section4 }.count
default: break
}
return num
}
此方法无法编译: 二元运算符' =='不能应用于类型' sectionNumber的操作数?'和' _'
这样做的正确方法是什么? 谢谢!
答案 0 :(得分:2)
您的代码存在一些问题:
ItemNumber
)命名。属性(例如枚举案例)应为小写(item1
)Int
或String
。你的代码有很多switch
语句来匹配带整数的枚举 - 你不需要这样做。以下是重写代码的方法:
public enum ItemNumber: Int {
case item1 // item1 is implicitly 0
case item2
case item3
case item4
case item5
case item6
}
public enum SectionNumber: Int {
case section1 = 0 // section1 is explicitly 0. You can start at any value.
case section2
case section3
case section4
}
public struct Item {
var itemNumber: ItemNumber?
var sectionNumber: SectionNumber?
var checkmark: Bool
init(sectionNumber: Int, itemNumber: Int, checkmark: Bool) {
self.itemNumber = ItemNumber(rawValue: itemNumber)
self.sectionNumber = SectionNumber(rawValue: sectionNumber)
self.checkmark = checkmark
}
}
你的控制器的功能:
func getNumOfItemsPerSection(section: Int) -> Int {
guard let sectionNumber = SectionNumber(rawValue: section) else { return 0 }
return self.items.filter({ $0.sectionNumber == sectionNumber }).count
}