I\'m just starting to learn swift. I\'m attempting to create an array of several random numbers, and eventually sort the array. I\'m able to create an array of one random number
How about this? Works in Swift 5 and Swift 4.2:
public extension Array where Element == Int {
static func generateRandom(size: Int) -> [Int] {
guard size > 0 else {
return [Int]()
}
return Array(0..
Usage:
let array = Array.generateRandom(size: 10)
print(array)
Prints e.g.:
[7, 6, 8, 4, 0, 3, 9, 2, 1, 5]
The above approach gives you unique numbers. However, if you need redundant values, use the following implementation:
public extension Array where Element == Int {
static func generateRandom(size: Int) -> [Int] {
guard size > 0 else {
return [Int]()
}
var result = Array(repeating: 0, count: size)
for index in 0..
A shorter version of the above using map():
public extension Array where Element == Int {
static func generateRandom(size: Int) -> [Int] {
guard size > 0 else {
return [Int]()
}
var result = Array(repeating: 0, count: size)
return result.map{_ in Int.random(in: 0..