generate a random array in swift

To generate a random array in Swift, you can use the shuffle() method of the Array class. Here's an example:

main.swift
var myArray = [1, 2, 3, 4, 5]
myArray.shuffle()
print(myArray)
63 chars
4 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.swift
var randomArray: [Int] = []
for _ in 1...10 {
    let randomInt = Int.random(in: 0...100)
    randomArray.append(randomInt)
}
print(randomArray)
145 chars
7 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