[swift] card

iOS 2015. 7. 23. 00:26
반응형

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

        }

    }

}


let ace = Rank.Ace

let aceRawValue = ace.rawValue


println( "aceRawValue: \(aceRawValue)" )


println("simple description : \(ace.simpleDescription())")


func isEqual(a: Rank, b: Rank) -> Bool {

    if a == b {

        return true

    }

    return false

}


println("equal: \(isEqual(Rank.Ace, Rank.Eight))")


println("equal: \(isEqual(Rank.Ace, Rank.Ace))")


if let convertedRank = Rank(rawValue: 3){

    let threeDescription = convertedRank.simpleDescription()

}


enum Suit: Int {

    case Spades = 1, Hearts, Diamonds, Clubs

    func simpleDescription() -> String {

        switch self {

        case .Spades:

            return "spades"

        case .Hearts:

            return "heart"

        case .Diamonds:

            return "diamonds"

        case .Clubs:

            return "clubs"

        }

    }

    func color() -> String {

        switch self {

        case .Spades, .Clubs:

            return "black"

        case .Hearts, .Diamonds:

            return "red"

        }

    }

}

let hearts = Suit.Hearts

let heartsDescription = hearts.simpleDescription()


let suit = Suit.Spades


println(heartsDescription)

println(suit.color())


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)

println(threeOfSpades)

let threeOfSpadesDescription = threeOfSpades.simpleDescription()

println(threeOfSpadesDescription)


var deck = [Card]()


for i in 1...12 {

    for j in 1...4 {

        let card = Card(rank: Rank(rawValue: i), suit: Suit(rawValue: j))

        deck.append(card)

    }

}


for card in deck {

    println(card.simpleDescription() + " (" + card.suit!.color() + ")")

}

반응형
: