Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of random numbers in Swift

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, but what's the best way to iterate this to create an array of several random numbers?

func makeList() {
   var randomNums = arc4random_uniform(20) + 1

    let numList = Array(arrayLiteral: randomNums)

}

makeList()
like image 748
eloist Avatar asked Jan 25 '15 18:01

eloist


People also ask

How do I generate a random array in Swift?

Overview. In Swift, we can get a random element from an array by using randomELement() . If the array is empty, nil is returned.

How do you generate random numbers in Swift?

To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.

What is the general form of random number generation in Swift?

arc4random_uniform(n) returns a random number between zero and the (parameter minus one). Note: Both arc4random() and arc4random_uniform() use the type UInt32 instead of the more typical Int.


1 Answers

In Swift 4.2 there is a new static method for fixed width integers that makes the syntax more user friendly:

func makeList(_ n: Int) -> [Int] {
    return (0..<n).map { _ in .random(in: 1...20) }
}

Edit/update: Swift 5.1 or later

We can also extend Range and ClosedRange and create a method to return n random elements:

extension RangeExpression where Bound: FixedWidthInteger {
    func randomElements(_ n: Int) -> [Bound] {
        precondition(n > 0)
        switch self {
        case let range as Range<Bound>: return (0..<n).map { _ in .random(in: range) }
        case let range as ClosedRange<Bound>: return (0..<n).map { _ in .random(in: range) }
        default: return []
        }
    }
}

extension Range where Bound: FixedWidthInteger {
    var randomElement: Bound { .random(in: self) }
}

extension ClosedRange where Bound: FixedWidthInteger {
    var randomElement: Bound { .random(in: self) }
}

Usage:

let randomElements = (1...20).randomElements(5)  // [17, 16, 2, 15, 12]
randomElements.sorted() // [2, 12, 15, 16, 17]

let randomElement = (1...20).randomElement   // 4 (note that the computed property returns a non-optional instead of the default method which returns an optional)

let randomElements = (0..<2).randomElements(5)  // [1, 0, 1, 1, 1]
let randomElement = (0..<2).randomElement   // 0

Note: for Swift 3, 4 and 4.1 and earlier click here.

like image 58
Leo Dabus Avatar answered Oct 21 '22 17:10

Leo Dabus