我希望有一个可以采用Integer值的枚举,并使用它来确定与它关联的情况并返回图像。以下是我要实现的目标,但我不太了解如何实现。非常感谢您的帮助!
enum Icon (input: Int) {
//use input value to check which case need to return image name
case 0...100
case 101...200
case 201+
var image: UIImage {
switch self {
case .0...100: return UIImage(named: "plane.png")!
case .101...200: return UIImage(named: "arrow.png")!
case .201+: return UIImage(named: "logo.png")!
}
}
}
答案 0 :(得分:3)
如果您坚持使用枚举,则可以使用以下方法:
enum Icon: String {
case plane: "plane.png"
case arrow: "arrow.png"
case logo: "logo.png"
static func image(for value: Int) -> UIImage {
let icon: Icon
switch value {
case 0...100:
icon = .plane
case 101...200:
icon = .arrow
case 200...:
icon = .logo
default:
fatalError("Invalid int value")
}
return UIImage(named: icon.rawValue)!
}
}
尽管可以肯定的是,下面的内容更简单:
func image(for value: Int) -> UIImage {
switch value {
case 0...100:
return UIImage(named: "plane.png")!
case 101...200:
return UIImage(named: "arrow.png")!
case 200...:
return UIImage(named: "logo.png")!
default:
fatalError("Invalid int value")
}
}