Checking for an element

You can check if there’s at least one occurrence of a specific element in an array by using contains(_:), which returns true if it finds the element in the array, and false if it doesn’t.

You can use this method to write a function that checks if a given player is in the game:

func isEliminated(player: String) -> Bool { return !players.contains(player)

}

Now you can use this function any time you need to check if a player has been eliminated:

print(isEliminated(player: "Bob"))

// > false

You could even test for the existence of an element in a specific range:

players[1...3].contains("Bob")

// > true

Now that you can get data out of your arrays, it’s time to look at mutable arrays and how to change their values.

results matching ""

    No results matching ""