George S. Kang
George S. Kang

Reputation: 21

Swift: Using an enum to represent the rank of Playing Cards

I am trying to make an enum to express the rank of Playing Cards, as per the following specs:

The Rank enum should only have three cases: .ace, .numeric and .face. .ace represents an Ace, .numeric represents a number card, and .face represents a face card as JQK.

We also want to have a variable order to return the rank of the integer for printing (for example, a "Q" would return 12.

The enum produce the following:

var a = Rank.ace
var b = Rank.numeric(pipsCount: 7)
var c = Rank.face("Q")
print("\(a.order)") \\prints: 1
print("\(b.order)") \\prints: 7
print("\(c.order)") \\prints: 12

So far my problem is with getting it to print 12 for "Q".

I used:

    case ace
    case numeric(pipsCount: Int)
    case face(String)

To make the cases

And then a switch to make the other stuff

          switch self {
          case .ace:
               return 1
          case .numeric(let pipsCount):
            return pipsCount
          case .face
               return 0
        }

But I'm just not sure how to set up care .face because I'm not sure how do i convert the input from JQK into 11, 12, and 13 respectively?

Upvotes: 2

Views: 292

Answers (1)

Rob C
Rob C

Reputation: 5073

Since you didn't name the associated value explicitly you can extract it using any name you like. In this example I chose id:

enum Rank {
    case ace
    case numeric(pipsCount: Int)
    case face(String)

    var order: Int {
        switch self {
        case .ace:
            return 1
        case .numeric(let pipsCount):
            return pipsCount
        case .face(let id):
            switch id {
            case "J":
                return 11
            case "Q":
                return 12
            case "K":
                return 13
            default:
                return 0
            }
        }
    }
}

Upvotes: 4

Related Questions