將關聯值與枚舉語句結合使用枚舉可以非常靈活。第一示例:
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
和第二個例子:
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
不需要擴展。如果你確實想靜態值,你可以這樣做:
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
這可能比將在switch語句中的固定面值整潔。