Swift - Associated value or extension for an Enum

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

    Shorter and safer code:

    import UIKit
    
    enum Icon: String {
    
        case plane, arrow, logo, flag
    
        var image: UIImage {
    
            // If the image is not available, provide a default value so we dont force optional unwrapping
            return UIImage(named: "\(self.rawValue).png") ?? UIImage()
        }
    
        var color: UIColor {
            switch self {
            case .plane: return UIColor.green
            case .arrow: return UIColor.green
            case .logo: return UIColor.green
            case .flag: return UIColor.green
            }
        }
    }
    
    // Usage
    Icon.plane.color
    Icon.arrow.image
    

提交回复
热议问题