Appending elements

If new players want to join the game, they need to sign up and add their names to the array. Eli is the first player to join the existing four players. You can add Eli to the end of the array using the append(_:) method:

players.append("Eli")

If you try to append anything other than a string, the compiler will show an error. Remember, arrays can only store values of the same type. Also, append(_:) only works with mutable arrays.

The next player to join the game is Gina. You can append her to the game another way, by using the += operator:

players += ["Gina"]

The right-hand side of this expression is an array with a single element, the string "Gina". By using +=, you’re appending the elements of that array to players. Now the array looks like this:

print(players)

// > ["Alice", "Bob", "Cindy", "Dan", "Eli", "Gina"]

Here, you added a single element to the array but you see how easy it would be to append multiple items by adding more names after Gina’s.

results matching ""

    No results matching ""