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

To get a sample of 5 elements from an array with replacement in Swift, you can use the randomElement() function along with a loop to generate a new array of random elements.

main.swift
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
var sampleArray = [Int]()

while sampleArray.count < 5 {
    if let randomElement = array.randomElement() {
        sampleArray.append(randomElement)
    }
}

print(sampleArray)
222 chars
11 lines

In this example, the array variable contains the elements that we want to sample from. We create an empty array called sampleArray to store the sampled elements. Then, we use a loop to randomly select elements from the original array using randomElement(). The loop continues until we have sampled 5 elements and added them to the sampleArray.

Note that because we are sampling with replacement, it's possible for the same element to be sampled multiple times. If you want to sample without replacement, you can modify the code to remove the selected element from the original array using remove(at:) after it's been added to the sample array.

gistlibby LogSnag