create array of random numbers in swift

前端 未结 5 2079
面向向阳花
面向向阳花 2021-02-14 19:19

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

5条回答
  •  离开以前
    2021-02-14 20:03

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

提交回复
热议问题