2016-10-03 83 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