Phontaine Judd
Phontaine Judd

Reputation: 438

How to allow a struct variable to use multiple enums?

Probably a weird question, but here goes. I'm a noob at enums and have just started using them in my code. I have a struct Points that has several variables, one of which is an enum PointCategory. The issue is, sometimes I want the var itemCategory to also allow a different enum: BudgetCategory.

I know I can't do this:

struct Points {
    var itemCategory: PointCategory || BudgetCategory
}

because it produces an error. But that's essentially what I want to do. I guess it's like subclassing an enum? Or something like that. Is there a way to allow one of my struct variables to use more than one enum?

Here's the current code:

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
}

Or am I going about this completely wrong? I'm open to explanations and suggestions.

Upvotes: 0

Views: 292

Answers (1)

vadian
vadian

Reputation: 285064

The context is unclear but you could use generics

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
}

Upvotes: 2

Related Questions