我意识到Swift书籍提供了一个随机数生成器的实现。复制和粘贴这个实现是最佳实践吗?或者有没有这样的库,我们现在就可以使用?


当前回答

Xcode 14, swift 5

public extension Array where Element == Int {
    static func generateNonRepeatedRandom(size: Int) -> [Int] {
        guard size > 0 else {
            return [Int]()
        }
        return Array(0..<size).shuffled()
    }
}

使用方法:

let array = Array.generateNonRepeatedRandom(size: 15)
print(array)

输出

其他回答

你可以像这样使用GeneratorOf:

var fibs = ArraySlice([1, 1])
var fibGenerator = GeneratorOf{
    _ -> Int? in
    fibs.append(fibs.reduce(0, combine:+))
    return fibs.removeAtIndex(0)
}

println(fibGenerator.next())
println(fibGenerator.next())
println(fibGenerator.next())
println(fibGenerator.next())
println(fibGenerator.next())
println(fibGenerator.next())

你可以像在C中那样做:

let randomNumber = arc4random()

推断randomNumber类型为UInt32(32位无符号整数)

 let MAX : UInt32 = 9
 let MIN : UInt32 = 1

    func randomNumber()
{
    var random_number = Int(arc4random_uniform(MAX) + MIN)
    print ("random = ", random_number);
}

斯威夫特4.2

Swift 4.2在标准库中包含了一个原生的、功能相当全的随机数API。(Swift Evolution提案SE-0202)

let intBetween0to9 = Int.random(in: 0...9) 
let doubleBetween0to1 = Double.random(in: 0...1)

所有的数字类型都有静态随机数(in:),它接受范围并返回给定范围内的随机数

Xcode 14, swift 5

public extension Array where Element == Int {
    static func generateNonRepeatedRandom(size: Int) -> [Int] {
        guard size > 0 else {
            return [Int]()
        }
        return Array(0..<size).shuffled()
    }
}

使用方法:

let array = Array.generateNonRepeatedRandom(size: 15)
print(array)

输出