在同一枚举函数中调用Swift枚举大小写

时间:2020-06-02 20:44:11

标签: swift enums case

我正试图了解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放入字符串的方法。

2 个答案:

答案 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")
}