Jared Pieniazek
Jared Pieniazek

Reputation: 41

How to Access Objects in a Class

I am trying to make a function create a new player (registerNewPlayer) from a registration form. The problem I am running into is that once the player object is created, I cannot access the player information to change variables such as the player name or the gold value of the player. How do I access objects in a class without an identifier or how can I create a function create a new player with an identifier?

class Players {

    var name: String
    var gold: Int
    var accountPassword: String

    init (name:String, gold: Int, accountPassword: String) {
        self.name = name; self.gold = gold; self.accountPassword = accountPassword
    }
}

func registerNewPlayer (playerName: String, password: String) -> Players {
    let registree = Players(name: playerName, gold: 0, accountPassword: password)
    return registree
}

registerNewPlayer(playerName: "Bob", password: "abc")

Upvotes: 1

Views: 142

Answers (2)

Jared Pieniazek
Jared Pieniazek

Reputation: 41

The fix was to place the returned object into an array of players in the init {} statement of the Players class. This allows the players to be identified by the index number of the array.

Upvotes: 2

Chris
Chris

Reputation: 4391

You need to assign the new player to a variable so you can access it later.

var playerOne = registerNewPlayer(playerName: "Bob", password: "abc")

print(playerOne.name) // Prints "Bob"

Upvotes: 0

Related Questions