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.swift134 chars7 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