1

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

1 回答 1

2

为避免生成相同的报价,请跟踪struct名为 的属性中的最后一个报价lastQuote。然后将最大随机数减 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())
}
于 2016-10-03T03:39:52.013 回答