Reputation: 177
I'm trying to get my head around Swift enums and in doing so have taken myself off a tutorial track by trying to return a string from a function within the same enum...
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()
My code starts with a implicit assignment which lists the top 5 bands of all time (some of you may disagree with me on this..). Within the same enum I have a function which will print:
The band \(???) has been ranked no.\(self.rawValue) of all time
I've chosen .acdc
so I'm looking for the function to return:
The band acdc has been ranked no.5 of all time
Whilst I can pull the rawValue (5) I can't seem to find a way to get the acdc
into the string.
Upvotes: 0
Views: 423
Reputation: 19884
While you can use self
, I would advise against it because with enum
names you have limitations, like having to use pink_floyd
.
Instead I would recommend adding a String
property that returns a display name depending on the value of the 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")
}
Upvotes: 0
Reputation: 54466
Just use self
:
func printRating() {
print("The band \(self) has been ranked no.\(self.rawValue) of all time")
}
The self
is the reference to its own value which is acdc
in this case.
Upvotes: 1