
- Swift - Home
- Swift - Overview
- Swift - Environment
- Swift - Basic Syntax
- Swift - Variables
- Swift - Constants
- Swift - Literals
- Swift - Comments
- Swift Operators
- Swift - Operators
- Swift - Arithmetic Operators
- Swift - Comparison Operators
- Swift - Logical Operators
- Swift - Assignment Operators
- Swift - Bitwise Operators
- Swift - Misc Operators
- Swift Advanced Operators
- Swift - Operator Overloading
- Swift - Arithmetic Overflow Operators
- Swift - Identity Operators
- Swift - Range Operators
- Swift Data Types
- Swift - Data Types
- Swift - Integers
- Swift - Floating-Point Numbers
- Swift - Double
- Swift - Boolean
- Swift - Strings
- Swift - Characters
- Swift - Type Aliases
- Swift - Optionals
- Swift - Tuples
- Swift - Assertions and Precondition
- Swift Control Flow
- Swift - Decision Making
- Swift - if statement
- Swift - if...else if...else Statement
- Swift - if-else Statement
- Swift - nested if statements
- Swift - switch statement
- Swift - Loops
- Swift - for in loop
- Swift - While loop
- Swift - repeat...while loop
- Swift - continue statement
- Swift - break statement
- Swift - fall through statement
- Swift Collections
- Swift - Arrays
- Swift - Sets
- Swift - Dictionaries
- Swift Functions
- Swift - Functions
- Swift - Nested Functions
- Swift - Function Overloading
- Swift - Recursion
- Swift - Higher-Order Functions
- Swift Closures
- Swift - Closures
- Swift-Escaping and Non-escaping closure
- Swift - Auto Closures
- Swift OOps
- Swift - Enumerations
- Swift - Structures
- Swift - Classes
- Swift - Properties
- Swift - Methods
- Swift - Subscripts
- Swift - Inheritance
- Swift-Overriding
- Swift - Initialization
- Swift - Deinitialization
- Swift Advanced
- Swift - ARC Overview
- Swift - Optional Chaining
- Swift - Error handling
- Swift - Concurrency
- Swift - Type Casting
- Swift - Nested Types
- Swift - Extensions
- Swift - Protocols
- Swift - Generics
- Swift - Access Control
- Swift - Function vs Method
- Swift - SwiftyJSON
- Swift - Singleton class
- Swift Random Numbers
- Swift Opaque and Boxed Type
Swift Array - shuffle Function
The shuffle() function of an array is used to shuffle the elements present in the given array. It shuffles elements randomly so whenever you run the code you will get different output. This function works only for mutating collections such as arrays, it does not work with non-mutating collections. Mutating collections are those collections that can be modified whereas non-mutating collections are those collections that cannot be modified, if we try to modify them we will get an error.
For example, we have an array = [34, 10, 38, 9, 19]. Now using the shuffle() function we shuffle the elements of the given array. Hence the resultant array is [9, 38, 19, 34, 10].
We can use the shuffle() function in two different types −
- shuffle() function
- shuffle(using:) function
Swift Array shuffle() Function
The shuffle() function is used to shuffle the elements of the given array randomly. It does not change the elements instead it only modifies their position. The complexity of this function is O(n), where n is the size of the given array.
Syntax
Following is the syntax of the shuffle() function −
func shuffle()
Parameters
This function does not take any parameter.
Return Value
This function returns an array with shuffled elements.
Now we will discuss how to use the shuffle() function with the help of the following examples:
Example 1
Swift program to shuffle the elements of the given array using the shuffle() function.
import Foundation // Array of integer type var arr1 = [4, 5, 6, 7, 88, 89] print("Original Array:", arr1) // Shuffling the array elements arr1.shuffle() // Display the result print("Shuffled Array:", arr1) // Array of string type var arr2 = ["Swift", "Java", "C++"] print("\nOriginal Array:", arr2) // Shuffling the array elements arr2.shuffle() // Display the result print("Shuffled Array:", arr2) // Array of mixed type var arr3: [Any] = [3.2, "Swift", 4, "Hello", false] print("\nOriginal Array:", arr3) // Shuffling the array elements arr3.shuffle() // Display the result print("Shuffled Array:", arr3)
Output
Original Array: [4, 5, 6, 7, 88, 89] Shuffled Array: [5, 6, 89, 7, 4, 88] Original Array: ["Swift", "Java", "C++"] Shuffled Array: ["Swift", "C++", "Java"] Original Array: [3.2, "Swift", 4, "Hello", false] Shuffled Array: ["Swift", false, 4, "Hello", 3.2]
Example 2
Swift program to shuffle the elements of a 2-D array using the shuffle() function. Here we shuffle each row of the given 2-D array.
import Foundation // Defining 2-D array var twoDArray = [ [3, 5, 7, 8, 9], [3, 4, 6, 8, 9], [1, 3, 5, 75, 4], ] // Print the original print("Original 2D Array:") for row in twoDArray { print(row) } // Shuffling 2-D array twoDArray.shuffle() // Print Shuffled array print("\nShuffled 2D Array:") for row in twoDArray { print(row) }
Output
Original 2D Array: [3, 5, 7, 8, 9] [3, 4, 6, 8, 9] [1, 3, 5, 75, 4] Shuffled 2D Array: [3, 5, 7, 8, 9] [3, 4, 6, 8, 9] [1, 3, 5, 75, 4]
Swift Array shuffle(using: ) Function
The shuffle(using:) function is used to shuffle the elements of the given array according to the given randomness generator. You can use a predefined random number generator or a custom random number generator. The complexity of this function is O(n), where n represents the length of the array.
Syntax
Following is the syntax of the shuffle(using:) function −
func shuffle<T>(using generator: inout T) where T : RandomNumberGenerator
Parameters
This function takes only one parameter which is a generator. The generator represents the random number generator that is used to shuffle the array.
Return Value
This function returns an array with shuffled elements.
Now we will discuss how to use the shuffle(using:) function with the help of the following examples:
Example 1
Swift program to shuffle the elements of the given array using shuffle(using:) function.
import Foundation // Defining an array of integer type var inputArr: [Int] = [10, 23, 11, 19, 20] print("Original Array:", inputArr) // Create a custom random number generator var randomGenerator = SystemRandomNumberGenerator() // Shuffle the array with a custom random generator inputArr.shuffle(using: &randomGenerator) print("Shuffled Array: \(inputArr)")
Output
Original Array: [10, 23, 11, 19, 20] Shuffled Array: [19, 20, 10, 11, 23]
Example 2
Swift program to shuffle the array using a custom random generator and then find their sum.
import Foundation // Defining an array of integer type var inputArr: [Int] = [10, 23, 11, 19, 20] print("Original Array:", inputArr) // Create a custom random number generator var randomGenerator = SystemRandomNumberGenerator() // Shuffle the array with a custom random generator inputArr.shuffle(using: &randomGenerator) print("Shuffled Array: \(inputArr)") // Calculating the sum of the array elements using reduce() function let sum = inputArr.reduce(0, +) print("Sum: \(sum)")
Output
Original Array: [10, 23, 11, 19, 20] Shuffled Array: [20, 11, 23, 10, 19] Sum: 83