I just start to learn programming and I am trying to work out the experiment in Swift programming book.
It asks "“Write a function that compares two Rank values by comparing their raw values.”
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.toRaw())
}
}
I wrote the following function
func compare(a:Rank,b:Rank) -> Bool{
return a.toRow() > b.toRow()}
I knew it is wrong, because toRow() is function of the members of Rank. But I don't know what is the data type of the members of the Rank.
There is a typo in your code which will probably prevent it from compiling correctly. The method is toRaw
not toRow
.
Your larger question is, "what is the data type of members of Rank." The exercise declares Rank the following way: enum Rank: Int
so the type is Int.
Unfortunately the wording in The Swift Programming Language makes it easy to overlook, but there is a subtle difference in the declaration of Enums that have members with raw values, and Enums that have associated values (or no values).
Here's the example of raw Enums from the book:
enum ASCIIControlCharacter: Character { // note type declaration
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
}
The key is the type declaration : Character
which follows the name of the Enum. If you try to declare it like this:
enum ASCIIControlCharacter { // missing type declaration
case Tab = "\t" // won't work!
case LineFeed = "\n"
case CarriageReturn = "\r"
}
You will get error: enum case cannot have a raw value if the enum does not have a raw type
.
So the type of the raw value for each member has to match the declared type of the Enum.
Source: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-XID_190
The raw values are Ints. Ace = 1, Two = 2, ... King = 13. The toRaw() function called on a Rank returns this Int. Note that it is toRaw() not toRow().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With