Swift - Associated value or extension for an Enum

后端 未结 4 1846
有刺的猬
有刺的猬 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:08

    Using enums with associated values combined with switch statements you can be very flexible. A first example:

    enum Icon {
        case plane(img:UIImage, col:UIColor)
        case arrow(img:UIImage, col:UIColor)
        case logo(img:UIImage, col:UIColor)
        case flag(img:UIImage, col:UIColor)
    
        var values:(img:UIImage,col:UIColor) {
            switch self {
            case let .plane(image, color):
                return (image,color)
            case let .arrow(image, color):
                return (image,color)
            case let .logo(image, color):
                return (image,color)
            case let .flag(image, color):
                return (image,color)
            }
        }
    }
    
    
    
    var a = Icon.plane(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
    
    a.values.col
    a.values.img
    

    and a second example:

    enum Icon {
        case plane(img:UIImage, col:UIColor)
        case arrow(img:UIImage, col:UIColor)
        case logo(img:UIImage, col:UIColor)
        case flag(img:UIImage, col:UIColor)
    
        var img:UIImage {
            switch self {
            case let .plane(image, color):
                return image
            case let .arrow(image, color):
                return image
            case let .logo(image, color):
                return image
            case let .flag(image, color):
                return image
            }
        }
    
        var col:UIColor {
            switch self {
            case let .plane(image, color):
                return color
            case let .arrow(image, color):
                return color
            case let .logo(image, color):
                return color
            case let .flag(image, color):
                return color
            }
        }
    }
    
    
    
    var a = Icon.plane(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
    
    a.col
    a.img
    

    no need for extensions. And if you really do want static values, you could do this:

    struct MyIcon {
        static let plane = Icon.plane(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
        static let arrow = Icon.arrow(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
        static let logo = Icon.logo(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
        static let flag = Icon.flag(img: UIImage(named: "image.png")!, col: UIColor.blueColor())
    }
    
    MyIcon.arrow.col
    

    which might be tidier than placing the fixed literal values inside a switch statement.

提交回复
热议问题