Swift - Associated value or extension for an Enum

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

    More cleaner and readable

    enum Icon {
        case plane
        case arrow
        case logo
        case flag
    
        var image: UIImage {
            return value.image
        }
    
        var color: UIColor {
            return value.color
        }
    
        private var value: (image: UIImage, color: UIColor) {
            switch self {
            case .plane: return (UIImage(named: "plane.png")!, UIColor.green)
            case .arrow: return (UIImage(named: "arrow.png")!, UIColor.green)
            case .logo: return (UIImage(named: "logo.png")!, UIColor.green)
            case .flag: return (UIImage(named: "flag.png")!, UIColor.green)
            }
        }
    }
    
    // Use
    Icon.plane.image
    Icon.plane.color
    

提交回复
热议问题