user1658921 user1658921 - 3 months ago 8
Swift Question

Swift -- "alias" an instance of an object

Working on a simple card game to learn Swift and IOS programming. For this function, the following code will work:

func dealCards() {

for _ in 0...9 {

player1.cardDealt(deck.getNextCard())
player2.cardDealt(deck.getNextCard())
}
}


However, I would like to rotate the dealer. I know that I could duplicate the for loop within if/else blocks, but I would rather do something like this:

func dealCards() {

// Dealer is considered position 2
if player1.isDealer() {
let pos1 = player2
let pos2 = player1
}
else {
let pos1 = player1
let pos2 = player2
}
for _ in 0...9 {
pos1.cardDealt(deck.getNextCard())
pos2.cardDealt(deck.getNextCard())
}
}


I'm sure it's simple, but I can't seem to figure out how to alias my player objects to use them in this way.

Answer

The problem with your code seems to be that you are defining pos1 and pos2 inside each if statement, and thus these values cannot be accessed from outside these statements. You need to first define them outside the statements and then set their values inside.

This is how it would look in the end:

func dealCards() {
    let pos1: Player
    let pos2: Player

    // Dealer is considered position 2
    if player1.isDealer() {
        pos1 = player2
        pos2 = player1
    }
    else {
        pos1 = player1
        pos2 = player2
    }
    for _ in 0...9 {
        pos1.cardDealt(deck.getNextCard())
        pos2.cardDealt(deck.getNextCard())
    }
}

A more compact way to do this would be to swap the values using tuples and the ternary operator:

   func dealCards() {

    // Dealer is considered position 2
    let (pos1, pos2) = player1.isDealer() ? (player2, player1) : (player1, player2)
    //If player1 is the dealer, swap pos1 and pos2
    for _ in 0...9 {
        pos1.cardDealt(deck.getNextCard())
        pos2.cardDealt(deck.getNextCard())
    }
} 
Comments