2016-10-03 80 views
1

我在结构中使用GKRandomSource在视图中返回一个随机励志名言。有没有办法返回这个随机数并省略之前的输入?这样用户不会连续两次收到相同的报价。使用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

最好有每次数组的副本和你采取随机索引,从数组中删除它,然后随机从0到新的阵列大小 – Fonix

回答

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()) 
} 
+0

感谢您的响应; '1 ... 10'中的_不能在顶层传递。有什么我需要修复吗? (快速开始) – VegaStudios

+0

这只是如何使用RandomQuote结构的演示。你可以添加var rq = RandomQuote()作为类的一个属性,比如ViewController,并且在VC中的任何函数内部调用rq.getRandomInspiration()来获得一个引用。 – vacawama

+0

@VegaStudios,你觉得它有用吗? – vacawama