How do I append each element in an array?

Hi, I'm trying to create an array that holds every card in card deck. Instead of manually writing out 52 separate elements, I'm creating 4 identical arrays containing the 13 cards, appending them with their respective suits, and then will append the four arrays into one to have a full deck.

I can't figure out the syntax to append each element in the arrays. Can someone help me?

Here's what I've tried:


Could you please edit your question to include your code, as code? Many of readers (including myself :smile:) would gladly edit it and explain what's going on, but don't want to spend time transcribing that screenshot

1 Like

You need to do the append separate from the assignment or return. Unlike many other languages, Swift doesn’t automatically return the result of mutations like that. Instead, it thinks you want a reference to the append function. Someone else can explain that.

append only operates on the end of an array, it does not broadcast the argument to every element in the array. to do that, you want to use map:

let deck2:[String] =
    $0 + "OfDiamonds"

which will produce something like

    // ...

I'd invest into these simple extensions:

extension Array {
    func appending(_ element: Element) -> Self {
        var new = self
        return new
let newDeck = deck1.appending(" of diamonds")
print(newDeck) // ["ace", "2", "3", ... "Queen", "King", " of diamonds"]
protocol Addable {
    static func + (a: Self, b: Self) -> Self

extension String: Addable {}

extension Array where Element: Addable {
    func adding(_ add: Element) -> Self {
        map { element in
            element + add
let betterDeck = deck1.adding(" of diamonds")
print(betterDeck) // ["ace of diamonds", "2 of diamonds", "3 of diamonds", ...]

You may also define "+" and "+=":

array + element

But it may be non obvious would that mean "appending" or "adding" above.

@geniusPenguin .append adds the element to the end of the array. You can modify your second attempt to something like this:

func giveCardsSuits(deck: [String], suit: String) -> [String] {
    var result: [String] = []
    for card in deck {
       result.append(card + suit)
   return result

You can then do deck2 = giveCardsSuits(deck: deck1, suit: "OfDiamonds")

I recommend using the map function implementation suggested by @taylorswift but you can use the above one if you want a more conventional approach.