本文介绍了Swift-枚举的关联值或扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有关快速枚举的一般问题.
General question regarding swift enum.
我想创建一个"icon"枚举并将一个值关联"到该枚举大小写
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
这种事情有可能吗?
推荐答案
不幸的是,您无法基于枚举案例定义静态属性,但是可以使用计算属性和switch
来返回每种案例的值:
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
这篇关于Swift-枚举的关联值或扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!