Pop*_*nel 1 methods enums swift swift-playground
我一直在使用Xcode Playgrounds在Swift中乱搞.我知道Swift枚举比它们的Obj-C等价物强大得多.所以我想我将包含颜色的枚举作为成员值,并在枚举中添加一个方法来获取颜色的十六进制值.
但是,我收到错误 - "表达式解析为未使用的函数".我觉得这可能与让方法接受成员值作为参数有关,但我可能错了.代码如下.有人可以开导我吗?
enum Color {
case Red,Blue,Yellow
func hexValue (aColor: Color) -> String { //Find hex value of a Color
switch aColor {
case .Red:
return "#FF0000"
case .Yellow:
return "#FFFF00"
case .Blue:
return "#0000FF"
default:
return "???????"
}
}
}
Color.hexValue(Color.Red) //Error: "Expression resolves to an unused function"
Run Code Online (Sandbox Code Playgroud)
添加static到声明hexValue以创建可以从没有实例的类型调用的类型方法:
enum Color {
case Red,Blue,Yellow
static func hexValue (aColor: Color) -> String { //Find hex value of a Color
switch aColor {
case .Red:
return "#FF0000"
case .Yellow:
return "#FFFF00"
case .Blue:
return "#0000FF"
default:
return "???????"
}
}
}
Color.hexValue(Color.Red) // "#FF0000"
Run Code Online (Sandbox Code Playgroud)
或者你可以通过使它成为计算属性来使这更好:
enum Color {
case Red,Blue,Yellow
var hexValue: String {
get {
switch self {
case .Red: return "#FF0000"
case .Yellow: return "#FFFF00"
case .Blue: return "#0000FF"
}
}
}
}
Color.Red.hexValue // "#FF0000"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2352 次 |
| 最近记录: |