在Swift中处理枚举案例

时间:2019-05-07 08:14:43

标签: ios enums swift4.2 case-statement

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

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

编辑:

我需要这个,因为我有

实践 image
  

推,练习推荐

播放 image

  

PlayRecommendation,弹出

编辑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
        }
    }

处理图片

1 个答案:

答案 0 :(得分: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
 }
}