【问题标题】:handle cases of Enums in Swift处理 Swift 中的枚举案例
【发布时间】:2019-05-07 08:14:43
【问题描述】:

我们如何处理来自Enum's 响应的不同输入的相同案例

enum MyNotificationType: String, Codable {
        case practice = "push"
        case practice = "PracticeRecommendation"
        case play = "PlayRecommendation"
        case play = "pop"
    }

编辑:

我需要这个,因为我有共同的练习 image

推送,实践推荐

image

播放推荐,流行

编辑 2:

enum MyNotificationType: String, Codable {
    case push = "push"
    case practice = "PracticeRecommendation"
    case play = "PlayRecommendation"
    case pop  = "pop"
}

并添加了switch

private func showImage(_ type: MyNotificationType) {
        switch type {
        case .practiceRecommendation, .push:
            self.typeImgView.image = UIImage(named: "Practice")
            break
        case .play, .pop:
            self.typeImgView.image = UIImage(named: "Play")
            break
        }
    }

处理图片

【问题讨论】:

  • 您能否添加更多上下文,以便我给出更正确的答案?为什么需要一个案例处理两个不同的 rawValue?为什么不能将pushpracticeRecommendation 等单独声明为一个单独的案例?
  • @JoshuaFrancisRoman 我编辑我的问题
  • 您不能在枚举中创建相同的案例。
  • @MahendraGP 谢谢。我试图使其具有不同原始类型的独特案例。

标签: ios enums swift4.2 case-statement


【解决方案1】:

嗯。您可以使用具有关联类型的枚举,但除非您也更改 init(rawType),否则您将无法静态确保可能的字符串。不过,我不确定您要实现什么目标,因此可能会有不同的方式

enum MyNotificationType{
 case practice(value: String)
 case play(value: String)

 init(rawType: String){
    //define what case based on string, do error if you can't handle or use a unknown case
 }
}

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2017-12-09
    • 2021-09-22
    • 2021-09-25
    相关资源
    最近更新 更多