To generate a random array in Swift, you can use the shuffle()
method of the Array
class. Here's an example:
main.swift63 chars4 lines
This code creates an array with the numbers 1 through 5, shuffles the order of the elements, and then prints the resulting array to the console.
If you want to generate an array with a specific number of elements, you can use a for
loop to add random values to the array. Here's an example of how to generate an array of 10 random integers between 0 and 100:
main.swift145 chars7 lines
The Int.random(in: ...)
method generates a random integer within the specified range, and the loop adds each new value to the array. Finally, the resulting array is printed to the console.
gistlibby LogSnag