get a sample of 5 elements from an array in swift

To get a sample of 5 elements from an array in Swift, you can use the shuffled() method to shuffle the array and then take the first 5 elements of the shuffled array using the prefix(_:) method. Here's an example of how to do it:

main.swift
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let shuffledArray = array.shuffled()
let sample = Array(shuffledArray.prefix(5))
print(sample) // prints something like [7, 1, 5, 2, 9]
180 chars
5 lines

In this example, we first create an array of integers from 1 to 10. We then shuffle the array using the shuffled() method and create a new array called shuffledArray. Finally, we take the first 5 elements of shuffledArray using the prefix(_:) method and create a new array called sample. We print out sample to see the 5 randomly selected elements from array.

gistlibby LogSnag