The Swift programming language (Suit, Rank, Card)

By December 7, 2014 Coding Tips No Comments

Having a play with Swift the latest programming language from Apple, I really like the simplicity of the language.Below you can find a few extract from the book available for free here: The Swift programming language.I have also added my response to the experiment blocks that you can find all through the book.

// Playground - noun: a place where people can play
import UIKit

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"
            return String(self.rawValue)

The code above define the Rank enum.

let ace = Rank.Ace
let aceRawValue = ace.rawValue

func compare(rank1:Rank, rank2:Rank) ->Rank{
    if(rank1.rawValue > rank2.rawValue){
        return rank1
    return rank2

let hightestRank = compare(Rank.King, Rank.Eigth)

The rawValue property give us access to the numerical value of the enum, it makes it easy for us to compare them. Note that the enum type is Int and the first value is set to one, we don’t need to explicitly define the other values when the first one is define which save a lot of time. Here Two = 2, Three = 3, etc.

enum Suit:Int {
    case Spades, Hearts, Diamonds, Clubs
    func color() ->String{
        switch self{
        case .Spades,.Clubs:
            return "black"
        case .Diamonds, .Hearts:
            return "red"
    func simpleDescription() -> String{
        switch self{
        case .Diamonds:
            return "diamonds"
        case .Clubs:
            return "clubs"
        case .Hearts:
            return "hearts"
        case .Spades:
            return "spades"

Here we define the Suit enum, I have change the code a bit and specified the type of the enum, it will help later when we need to work with both Rank and Suit.

let diamond = Suit.Diamonds

We can easily retrieve the color of a Suit.

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return " The \(rank.simpleDescription()) of \(suit.simpleDescription())"

let threeOfSpades =  Card(rank: .Three, suit: .Spades)

We now define a Card struct that use Rank and Suit

func generateDeck() -> [Card]
    let numberOfCardsPerSuit = 13
    var deck = [Card]()
    for index in 0..<52
        let suit = Suit(rawValue: index / ranksPerSuit)
        let rank = Rank(rawValue: index % ranksPerSuit + 1)      
        let card = Card(rank: rank!, suit: suit!)
    return deck

var deck = generateDeck()

for card in deck{

Finally, we can generate a deck of cards. We go through the elements of each enum using the raw value (index for each element).

Done, it was easy!

Leave a Reply