Swift - Associated value or extension for an Enum

后端 未结 4 1843
有刺的猬
有刺的猬 2021-02-01 19:43

General question regarding swift enum.

I want to create an enum of \"icon\" and \"associate\" a value to the enum case

enum Icon {
  case plane
  case ar         


        
4条回答
  •  北海茫月
    2021-02-01 20:13

    Unfortunately you cannot define static properties based on enum cases, but you can use computed properties and switch to return values for each case:

    enum Icon {
        case plane
        case arrow
        case logo
        case flag
    
        var image: UIImage {
            switch self {
                case .plane: return UIImage(named: "plane.png")!
                case .arrow: return UIImage(named: "arrow.png")!
                case .logo: return UIImage(named: "logo.png")!
                case .flag: return UIImage(named: "flag.png")!
            }
        }
    
        var color: UIColor {
            switch self {
            case .plane: return UIColor.greenColor()
            case .arrow: return UIColor.greenColor()
            case .logo: return UIColor.greenColor()
            case .flag: return UIColor.greenColor()
            }
        }
    }
    
    // usage
    Icon.plane.color
    

提交回复
热议问题