Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare enum rank in swift (exercise in Swift book)

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.

like image 493
user2196600 Avatar asked Jul 02 '14 16:07

user2196600


2 Answers

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

like image 101
Brett Avatar answered Oct 10 '22 18:10

Brett


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().

like image 44
Connor Avatar answered Oct 10 '22 18:10

Connor