swift - 如何允许结构变量使用多个枚举?

标签 swift

这可能是一个奇怪的问题,但这里是。我是枚举的菜鸟,刚开始在我的代码中使用它们。我有一个结构 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/

相关文章:

ios - 将 3 种不同的信息加载到 3 种不同类型的细胞

ios - 获取用户属性 AWS Amplify iOS SDK

ios - 无法使用 removeFromParent : Swift 删除点击的 spriteNode

ios - 快速检测在谷歌地图上按下了哪个标记

ios - 在 iOS 12 中,当使用具有约束的自调整大小单元格创建 UICollectionView 时,重新加载布局时高度错误,直到我滚动

ios - 如何根据数据更改 UICollectionView 单元格宽度

Swift:确定树中的节点

swift - 从 Google map 中点击的叠加层获取纬度和经度

ios - 图像作为表格 View 的标题 Swift 3

快速将 bool 转换为 NSRange