swiftenumsassociated-objectassociated-typescomputed-values

Swift - Associated value or extension for an Enum


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 arrow
  case logo
  case flag
}

I want to create an associated image to the enum's value. And also an associated color to the enum value

So for instance if it was possible to do something like:

extension Icon.plane {
  var image = {
    get {
       return UIImage("plane.png")
    }
  }
  var color = {
    get {
       return UIColor.greenColor()
    }
  }
}


var image = Icon.arrow.image // the image associated to the enum
var color = Icon.arrow.color // the color associated to the enum

Is this type of thing possible?


Solution

  • 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