这可能是一个奇怪的问题,但这里是。我是枚举的菜鸟,刚开始在我的代码中使用它们。我有一个结构 Points
,它有几个变量,其中一个是枚举 PointCategory
。问题是,有时我希望 var itemCategory
也允许不同的枚举:BudgetCategory
。
我知道我不能这样做:
struct Points {
var itemCategory: PointCategory || BudgetCategory
}
因为它会产生错误。但这基本上就是我想做的。我想这就像继承一个枚举?或类似的东西。有没有办法允许我的一个结构变量使用多个枚举?
这是当前代码:
enum BudgetCategory: String {
case clothing = "Clothing"
case donations = "Donations"
case electronics = "Electronics"
case funMoney = "Fun Money"
case musicArt = "Music & Art"
case other = "Other"
case personalCare = "Personal Care"
case savings = "Savings"
case school = "School"
case sportsDance = "Sports & Dance"
case summerCamps = "Summer Camps"
case transportation = "Transportation"
}
enum PointCategory: String {
case outsideIncome = "outside income"
case fees = "fees"
case otherJobs = "other jobs"
case payday = "payday"
case dailyJobs = "daily jobs"
case dailyHabits = "daily habits"
case weeklyJobs = "weekly jobs"
case otherTransactions = "other transactions"
case all = "all"
case unpaid = "unpaid"
}
struct Points {
var user: String
var itemName: String
var itemCategory: PointCategory
var code: PointCode
var valuePerTap: Int
var itemDate: Double
var paid: Bool
}
还是我的做法完全错了?我乐于接受解释和建议。
最佳答案
上下文不清楚,但你可以使用泛型
protocol CustomCategory {}
enum BudgetCategory: String, CustomCategory {
...
}
enum PointCategory: String, CustomCategory {
...
}
struct Points<T : CustomCategory> {
var user: String
var itemName: String
var itemCategory: T
var code: PointCode
var valuePerTap: Int
var itemDate: Double
var paid: Bool
}
关于swift - 如何允许结构变量使用多个枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58461278/