Swift Program to Shuffle the Elements of an Array

Swift provide an in built function named as shuffle() to shuffle the elements of an array. This function takes a sequence or array and then shuffle the places of the elements present in the given array.


func shuffle()

Where this function does not take any parameter. Also it does not return any value instead it shuffle the places of the element in the given collection or array.


In the following swift example, we will create and initialise an array of string type, then we shuffle the elements of the array using shuffle() function and display output.

import Foundation
import Glibc

// Creating an array
var myfruites = ["Kiwi", "Orange", "Mango", "Apple", "Sweet Apple", "Papaya"]

print("Original array:", myfruites)

// Shuffle array elements

print("Shuffled array:", myfruites)


Original array: ["Kiwi", "Orange", "Mango", "Apple", "Sweet Apple", "Papaya"]
Shuffled array: ["Mango", "Orange", "Kiwi", "Papaya", "Sweet Apple", "Apple"]


So this is how we can shuffle the elements of the array. Here shuffle() function shuffle the elements randomly, so whenever you run the code you will get different placement of elements in the output.

Updated on: 24-Apr-2023


Kickstart Your Career

Get certified by completing the course

Get Started