我有3个枚举:计算类型(+,-),+类别(10个案例),-类别(15个案例)。
那么如何使用我的枚举,以便根据计算类型,模型的实例将接受所需的清单。
//Example of Model
class Transaction {
var typeOfCalculation: TypeOfCalculation
var category: CategoryForConsuption
}
enum TypeOfCalculation {
case income
case consuption
}
enum CategoryForConsuption{
case noCategories
case food
case cafesAndRestaurants
case manufacturedGoods
}
enum CategoryForIncome {
case salary
case debt repayment
}
逻辑如下:如果计算类型为消费,则更改为CategoryForConsuption,如果为收入,则更改为CategoryForIncome。
我编辑了模型:
enum Accounting {
case income(category: IncomeCategory)
case consumption(category: ConsumptionCategory)
}
enum ConsumptionCategory: String, CaseIterable {
case noCategories = "No categories"
case food = "Food"
case cafesAndRestaurants = "Cafes and Restaurants"
case manufacturedGoods = "Manufactured Goods"
case forceMajeure = "Force Majeure"
}
enum IncomeCategory: String, CaseIterable {
case salary = "Salary"
case deposit = "Deposit"
}
但是现在我遇到了新问题。因为我需要将所有这些用于我的数据模型(realM)。 我该怎么办?
这是我的旧数据模型:
@objc dynamic private var privateTypeOfCalculation: String = TypeOfCalculation.consumption.rawValue
var typeOfCalculation: TypeOfCalculation {
get { return TypeOfCalculation(rawValue: privateTypeOfCalculation)! }
set { privateTypeOfCalculation = newValue.rawValue }
}
@objc dynamic private var privateCategoryForConsuption: String = CategoryForConsuption.noCategories.rawValue
var categoryForConsuption: CategoryForConsuption {
get { return CategoryForConsuption(rawValue: privateCategoryForConsuption)! }
set { privateCategoryForConsuption = newValue.rawValue }
}
答案 0 :(得分:2)
您可以使TypeOfCalculation
拥有associated values:
enum TypeOfCalculation {
case consuption(category: CategoryForConsuption)
case income(category: CategoryForIncome)
}
然后您只需在模型中添加typeOfCalculation
:
class Transaction {
var typeOfCalculation: TypeOfCalculation
}
我还建议您重命名案例和枚举名称:
enum Calculation {
case consumption(category: ConsumptionCategory)
case income(category: IncomeCategory)
}
class Transaction {
var calculation: Calculation
}
然后您可以像这样打开calculation
:
switch transaction {
case consumption(let category):
...
case income(let category):
...
}