Skip to content

Instantly share code, notes, and snippets.

@markjamesm

markjamesm/CardDeck.Swift

Last active Apr 18, 2020
Embed
What would you like to do?
Deck of cards model in Swift 5
// Deck of cards model in Swift 5.
// Run in Swift playgrounds
// Value of AKQJ needs to be changed.
import Foundation
enum CardSuits: String, CaseIterable {
case Hearts = "Hearts"
case Spades = "Spades"
case Clubs = "Clubs"
case Diamonds = "Diamonds"
}
enum CardValue: Int, CaseIterable {
case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king
// case jack, queen, king, ace
}
struct PlayingCard {
var cardValue: CardValue
var cardSuit: CardSuits
init(value: CardValue, suit: CardSuits)
{
self.cardValue = value
self.cardSuit = suit
}
func cardName() {
print("\(cardValue) of \(cardSuit)")
}
}
class CardDeck {
var cardsRemaining: Int
var deck: [PlayingCard]
init() {
cardsRemaining = 52
deck = []
}
func createDeck() {
for suit in CardSuits.allCases {
for value in CardValue.allCases {
deck.append(PlayingCard(value: value, suit: suit))
}
}
}
func listDeck() {
var count = 0
for card in deck {
print(card)
count += 1
}
print(count)
}
func shuffleDeck() {
deck.shuffle()
}
func drawCard() {
// let cardDrawn = deck.randomElement()!
guard let cardDrawn = deck.popLast() else {
print("No cards left in deck!")
return
}
// deck.remove(at: cardDrawn)
if self.cardsRemaining >= 1 {
self.cardsRemaining -= 1
print("You drew:")
print(cardDrawn.cardName())
print(cardsRemaining)
}
else {
print("No cards left in deck!")
}
}
}
// Create our deck, shuffle it, and then draw a card.
var deck = CardDeck()
deck.createDeck()
deck.shuffleDeck()
deck.drawCard()
// Optional functionality
//deck.listDeck()
//deck.cardsRemaing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.