快速创建随机数数组 [英] create array of random numbers in swift

查看:121
本文介绍了快速创建随机数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚刚开始学习敏捷。
我正在尝试创建由几个随机数组成的数组,并最终对该数组进行排序。我可以创建一个随机数数组,但是最好的迭代方法是创建一个随机数数组?

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()

任何帮助都将不胜感激。

Any help is greatly appreciated.

推荐答案

Swift 4.2 中,有一个用于固定宽度整数的新静态方法,使语法更加用户友好:

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) }
}

编辑/更新: Swift 5.1或更高版本

我们可以还扩展了 Range ClosedRange 并创建了一种返回 n 随机元素:

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

注意:用于 Swift 3 ,4和4.1 ,以及更早的版本,请点击此处

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

这篇关于快速创建随机数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆