Skip to content

👩🏻‍💻 🧑🏽‍💻 Subscribe and Read us on Substack to Get Full Access to Our Posts


How to pick a random element from an array : Swift

In this tutorial, you will learn how to pick a random element from an array using Swift.

You will Need Mac, the latest Xcode to complete this tutorial.

Open Xcode and create a new playground titled “How to pick a random element from an array using Swift”

Create an array and run the randomElement() method on it.

let teslaCars = ["Model S", "Model X", "Model 3", "Cybertruck"]

print(teslaCars.randomElement() ?? "Nothing") 

Run and see the results

Keep in mind that at the moment of writing this post we used Xcode 11 and Swift 5.
If anything will change in the future, it is OK, just use the new API calls for the functions mentioned in this post.

Back To Top
Search