Search code examples
arraysswiftstringobject

How can I return the first element in an Object array and convert it to String in Swift?


I'm trying to make a card game and want to return the card on the top of the deck. Here's the creation of the deck:

struct Card{
    let val: String
    let suit: String
}

class Deck{
    var cards: [Card] = []
    
    init(){
        let vals = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"]
        let suits = ["Spades","Clubs","Hearts","Diamonds"]
        
        for suit in suits{
            for val in vals{
                cards.append(Card(val:val, suit:suit))
            }
        }
    }

I've created a getFirstCard function:

func getFirstCard() -> Card{
        return cards.removeFirst()
    }

While this works, it returns the Card object:

Card(val: "2", suit: "Spades")

My problem is that I'd like it to return as a string of "number + suit", so in this case, "2Spades". I've also tried returning Card.val and Card.suit only to get syntax errors. So how can I convert this into a String?


Solution

  • Your func getFirstCard() deletes the first card and returns it, it does notget the first card. To get the first card use cards.first. To return this as a String as you described, use this function in your class Deck:

     func getFirstCardAsString() -> String {
         if let firstCard = cards.first {
             return firstCard.val + firstCard.suit
         }
         return ""
     }
    

    EDIT-1:

    alternative approach to get the card as String

    struct Card {
        let val: String
        let suit: String
        
        func asString() -> String {  // <--- here
            self.val + self.suit
        }
    }
    

    and use it like this:

     let deck = Deck()
     let card = deck.getFirstCard()
     print("----> card: \(card.asString())")