Ios 用随机源生成随机数

Ios 用随机源生成随机数,ios,swift,random,shuffle,gameplay-kit,Ios,Swift,Random,Shuffle,Gameplay Kit,我在一个结构中使用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

我在一个结构中使用
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]
}

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

最好是有一个数组的副本,每次获取一个随机索引时,将其从数组中删除,然后从0随机到新的数组中进行响应<无法在顶层传递代码>for uu in 1…10。有什么我要修的吗?(从swift开始)这只是如何使用RandomQuote结构的演示。您可以将var rq=RandomQuote()添加为类(如ViewController)的属性,并在该VC中的任何函数内调用rq.getrandomQuote()以获取quote。