我正试图了解Swift枚举,并通过尝试从同一个枚举中的函数返回字符串来使自己摆脱了教程的轨道。
enum topFiveBands: Int {
case led_zeppilin = 1, queen, rush, pink_floyd, acdc
func printRating() {
print("The band \(???) has been ranked no.\(self.rawValue) of all time")
}
}
var myFavBand = topFiveBands.acdc
myFavBand.printRating()
我的代码从隐式赋值开始,该赋值列出了有史以来的前5个波段(其中有些人可能对此表示反对。)。在同一个枚举中,我有一个将打印的函数:
The band \(???) has been ranked no.\(self.rawValue) of all time
我选择了.acdc
,所以我正在寻找要返回的函数:
The band acdc has been ranked no.5 of all time
虽然我可以提取rawValue(5),但似乎找不到找到将acdc
放入字符串的方法。
答案 0 :(得分:1)
只需使用self
:
func printRating() {
print("The band \(self) has been ranked no.\(self.rawValue) of all time")
}
self
是对其自身值(在这种情况下为acdc
的引用)。
答案 1 :(得分:0)
虽然您可以使用self
,但我建议您不要这样做,因为使用enum
的名称会有局限性,例如必须使用pink_floyd
。
相反,我建议添加一个String
属性,该属性根据enum
的值返回显示名称
var displayName: String {
switch self {
case .pink_floyd: return "Pink Floyd"
case ...: // The rest
}
}
func printRating() {
print("The band \(displayName) has been ranked no.\(rawValue) of all time")
}