Reputation: 423
While reading a tutorial about a deck of card, here, I found:
enum Suit: Int, CustomStringConvertible {
case Clubs = 1, Diamonds, Hearts, Spades
var description: String {
return ["♣️", "♦️", "❤️", "♠️"][rawValue - 1]
}
}
works well in playground. I understand it should be a short syntax for:
enum Suit: Int, CustomStringConvertible {
case Clubs = 1, Diamonds, Hearts, Spades
var description: String {
switch self {
case .Spades:
return "♠️"
case .Clubs:
return "♣️"
case .Diamonds:
return "♦️"
case .Hearts:
return "♥️"
}
}
}
I couldn't find any documentation on this syntax. Does it have a name or is it described in the official documentation or any other place? Thanks for any contribution.
Upvotes: 1
Views: 207
Reputation: 17500
["♣️", "♦️", "❤️", "♠️"][rawValue - 1]
is not a special syntax. Here's how it would be broken down:
let array: [String] = ["♣️", "♦️", "❤️", "♠️"]
let index: Int = self.rawValue - 1
let symbol = array[index]
return symbol
Upvotes: 2
Reputation: 118781
This isn't any special syntax by itself. It's two separate things:
An array literal, ["♣️", "♦️", "❤️", "♠️"]
which is an Array<String>
a.k.a. [String]
Array subscripting syntax: myArray[i]
or, in this case, array[rawValue - 1]
where array
is the literal from #1.
["♣️", "♦️", "❤️", "♠️"][rawValue - 1]
just means the rawValue - 1
th entry of that array. It relies on the fact that the enum is declared with enum Suit: Int
so that each value has an underlying rawValue
.
Upvotes: 3