【问题标题】:Generating random numbers with GKRandomSource使用 GKRandomSource 生成随机数
【发布时间】:2016-10-03 02:46:13
【问题描述】:

我在一个结构中使用GKRandomSource 在视图中返回一个随机的励志名言。有没有办法返回该随机数并省略先前的条目?这样用户就不会连续两次收到相同的报价。

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

【问题讨论】:

  • 最好有一个数组的副本,每次取随机索引时,将其从数组中删除,然后从 0 随机到新数组大小

标签: ios swift random shuffle gameplay-kit


【解决方案1】:

为避免生成相同的报价,请跟踪名为lastQuotestruct 属性中的最后一个报价。然后将最大随机数减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())
}

【讨论】:

  • 感谢您的回复; for _ in 1...10 不能在顶层传递。有什么我必须解决的吗? (迅速开始)
  • 这只是一个演示如何使用 RandomQuote 结构。您可以将 var rq=RandomQuote() 添加为 ViewController 等类的属性,并在该 VC 中的任何函数内调用 rq.getRandomInspiration() 以获取报价。
猜你喜欢
  • 2015-03-14
  • 1970-01-01
  • 2013-11-09
  • 1970-01-01
  • 2021-05-24
  • 2014-09-21
  • 2019-08-11
  • 2015-06-18
  • 1970-01-01
相关资源
最近更新 更多