scottevans93
scottevans93

Reputation: 1079

.append() to a Collection of custom Structs

I have a custom struct made for Creating, Shuffling and Dealing Playing cards.

struct Card {
    let pip : Pip
    let suit : Suit

    var isFaceCard : Bool {
        return pip.rawValue > 10
    }

    var color : CardColor {
        return suit.color
    }
}

Secondly I have a Dictionary of players initialised with each player having a Collection of Cards.

 var Players = ["Scott": [Card](), "Bob": [Card](), "John": [Card]()]

To effectively deal from my already shuffled deck, I plan to loop through the players' dictionary twice and deal one card per time, as would happen live.

Is it possible to simple append a Card type to the Card collection? My attempts haven't seemed to work. d being a shuffled Deck (Collection) of Card types.

Players["Scott"].append(d.deal())

EDIT1

With using Structs for each Player i have added this

struct Player {
   let name : String
   var cards : [Card]
}
var Players = [Player]()
Players.append(Player(name:"Scott"))

Do i have to give the player their "cards" upon initialisation or can i deal them at a later time? As the above code produces an error.

Players.append(Player(name:"Scott", cards: [Card]()))

Would the above be correct?

Upvotes: 3

Views: 251

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

Direct answer:

If a player can possess an array of cards, then a Player should be a struct and this struct should contain an array of cards as property. I suggest not using dictionaries at all here.

After your edit:

You're on the right track.

You don't have to give the player their cards at initialization if you create an initializer yourself for your struct:

struct Player {
    let name : String
    var cards : [Card] = []

    init(name: String) {
        self.name = name
    }
}

Doing so cancels the automatic generation of a memberwise initializer and only yours will be available.

But if you want to keep the automatic memberwise initializer, you can pass an empty array of cards like this at initialization:

struct Player {
    let name : String
    var cards : [Card]
}

let joe = Player(name: "Joe", cards: [])

After your comments:

If you have all your players in an array, you can fetch a specific player by using indexOf with a closure predicate, like this for example:

struct Player {
    let name : String
    var cards : [Card] = []

    init(name: String) {
        self.name = name
    }

    func fold() {
        print("\(name) just folded")
    }
}

var players = [Player]()
players.append(Player(name: "Joe"))
players.append(Player(name: "Jane"))
players.append(Player(name: "Jack"))
players.append(Player(name: "Janice"))

if let janeIndex = players.indexOf({ $0.name == "Jane" }) {
    players[janeIndex].fold()
}

Let's say you want all players to fold but one, you could use filter:

let notJack = players.filter { $0.name != "Jack" }
notJack.forEach { $0.fold() }

Upvotes: 1

Related Questions