get a sample of 5 elements from an array without replacement in swift

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

main.swift
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

let shuffledArray = array.shuffled()
let sample = shuffledArray.prefix(5)

print(sample)
134 chars
7 lines

This code first creates an array of integers from 1 to 10. It then shuffles the array using the shuffled() function and takes the first 5 elements of the shuffled array using the prefix function. Finally, it prints the sample array.

Note that this approach is efficient for relatively small arrays, but if your array is very large and you only need a small sample, it may be more efficient to use a different sampling method such as reservoir sampling.

gistlibby LogSnag