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


当前回答

斯威夫特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:),它接受范围并返回给定范围内的随机数

其他回答

Swift 4.2编辑

从Swift 4.2开始,你可以使用Swift自己的本地函数,而不是使用导入的C函数arc4random_uniform()。

// Generates integers starting with 0 up to, and including, 10
Int.random(in: 0 ... 10)

你也可以使用random(in:)来获取其他原始值的随机值;比如Int型,Double型,Float型,甚至Bool型。

Swift版本< 4.2

该方法将在给定的最小值和最大值之间生成一个随机Int值

func randomInt(min: Int, max: Int) -> Int {
    return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
var randomNumber = Int(arc4random_uniform(UInt32(5)))

这里5将确保随机数是从0到4生成的。您可以设置相应的值。

斯威夫特4.2

拜拜导入Foundation C库arc4random_uniform()

// 1  
let digit = Int.random(in: 0..<10)

// 2
if let anotherDigit = (0..<10).randomElement() {
  print(anotherDigit)
} else {
  print("Empty range.")
}

// 3
let double = Double.random(in: 0..<1)
let float = Float.random(in: 0..<1)
let cgFloat = CGFloat.random(in: 0..<1)
let bool = Bool.random()

使用random(in:)从范围中生成随机数字。 randomElement()返回nil如果范围是空的,所以你打开返回的Int?用if let。 使用random(in:)生成随机Double、Float或CGFloat,使用random()返回随机Bool类型。

更多@官方

我用这段代码生成一个随机数:

//
//  FactModel.swift
//  Collection
//
//  Created by Ahmadreza Shamimi on 6/11/16.
//  Copyright © 2016 Ahmadreza Shamimi. All rights reserved.
//

import GameKit

struct FactModel {

    let fun  = ["I love swift","My name is Ahmadreza","I love coding" ,"I love PHP","My name is ALireza","I love Coding too"]


    func getRandomNumber() -> String {

        let randomNumber  = GKRandomSource.sharedRandom().nextIntWithUpperBound(fun.count)

        return fun[randomNumber]
    }
}

例如10(0-9)之间的随机数;

import UIKit

let randomNumber = Int(arc4random_uniform(10))

非常简单的代码-简单和简短。