Updating elements

Frank has decided that everyone should call him Franklin from now on. You could remove the value “Frank” from the array and then add “Franklin”, but that’s just too much work for a simple task. Instead, you should use the subscript syntax to update the name:

print(players)

// > ["Alice", "Bob", "Dan", "Eli", "Frank"] players[4] = "Franklin"

print(players)

// > ["Alice", "Bob", "Dan", "Eli", "Franklin"]

You have to be careful not to use an index beyond the bounds of the array, or your app will crash.

As the game continues, some players are eliminated and new ones come to replace them. Luckily, you can also use subscripting with ranges to update multiple values in a single line of code:

players[0...1] = ["Donna", "Craig", "Brian", "Anna"] print(players)

// > ["Donna", "Craig", "Brian", "Anna", "Dan", "Eli", "Franklin"]

This code replaces the first two players, Alice and Bob, with the four players in the new players array. As you can see, the size of the range doesn’t have to be equal to the size of the array that holds the values you’re adding.

results matching ""

    No results matching ""