Delah
Delah

Reputation: 41

A variable in a variable

Is it possible to place a variable in a variable?

I'm trying to make a game. In this game there are two players. I don't want to type every action twice, but with different players, I would like to use the same thing that's possible in strings.

print("String \(variable) rest of string")

How can I accomplish the same in a variable?

var playerActive : String
var player1Score = 100
var player2Score = 100

if (x==0){
    playerActive = "player1"
}else{
    playerActive = "player2"
}

if (\(playerAvtive)Score) <= 0){ //Must become player1Score or player2Score
    print("You lost...")
}

I found the same question for other languages but not for Swift.

Upvotes: 2

Views: 90

Answers (1)

shallowThought
shallowThought

Reputation: 19602

Create a Player class:

class Player {
    var score = 0
}

let player1 = Player()
let player2 = Player()
var playerActive = player1

if (x == 0){
    playerActive = player1
} else{
    playerActive = player2
}

if playerActive.score <= 0 {
    print("You lost...")
}

I recommend against using a struct instead of a class, as you might have to check the winner using ===.

if someoneWon && activePlayer === player1 {
    print("Player 1 won!")
}

Upvotes: 3

Related Questions