简体   繁体   English

用GKRandomSource生成随机数

[英]Generating random numbers with GKRandomSource

I am using GKRandomSource in a struct to return a random inspirational quote in the view. 我在结构中使用GKRandomSource在视图中返回随机的鼓舞人心的报价。 Is there a way to return that random number and omit the prior entry? 有没有办法返回该随机数并忽略先前的输入? That way the user doesn't receive the same quote twice in a row. 这样,用户不会连续两次收到相同的报价。

let inspiration = [
    "You are looking rather nice today, as always.",
    "Hello gorgeous!",
    "You rock, don't ever change!",
    "Your hair is looking on fleek today!",
    "That smile.",
    "Somebody woke up on the right side of bed!"]

func getRandomInspiration() -> String {
    let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(inspiration.count)
    return inspiration[randomNumber]
}

To keep from generating the same quote, keep track of the last one in a struct property called lastQuote . 为了避免产生相同的报价,请在名为lastQuotestruct属性中跟踪最后一个lastQuote Then reduce the max random number by 1, and if you generate the same as the lastQuote , use max instead. 然后将最大随机数减1,如果生成的结果与lastQuote相同,则使用max代替。

struct RandomQuote {
    let inspiration = [
        "You are looking rather nice today, as always.",
        "Hello gorgeous!",
        "You rock, don't ever change!",
        "Your hair is looking on fleek today!",
        "That smile.",
        "Somebody woke up on the right side of bed!"]

    var lastQuote = 0

    mutating func getRandomInspiration() -> String {
        let max = inspiration.count - 1
        // Swift 3
        // var randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: max)
        var randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(max)
        if randomNumber == lastQuote {
            randomNumber = max
        }
        lastQuote = randomNumber
        return inspiration[randomNumber]
    }
}

var rq = RandomQuote()
for _ in 1...10 {
    print(rq.getRandomInspiration())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM