2017-05-09 171 views
-2

我對Swift和一般編程非常陌生,所以請耐心等待,而我試圖弄清楚這一點。如何在不重複Swift的情況下生成隨機數

我一直在從樹屋跟隨Swift的初學者課程,並設法開發一個簡單的應用程序,生成隨機引號。到現在爲止還挺好。現在,在開始學習更高級的課程之前,我想先試着更新現有的應用程序,以確保在繼續前進行一些紮實的練習。

所以這裏是我的問題:我設法通過GameKit框架生成一個隨機數,但問題是有時引號會連續出現。我怎樣才能避免這種情況發生?

這裏是我的代碼:

import GameKit 

struct FactProvider { 
    let facts = [ 
     "Ants stretch when they wake up in the morning.", 
     "Ostriches can run faster than horses.", 
     "Olympic gold medals are actually made mostly of silver.", 
     "You are born with 300 bones; by the time you are an adult you will have 206.", 
     "It takes about 8 minutes for light from the Sun to reach Earth.", 
     "Some bamboo plants can grow almost a meter in just one day.", 
     "The state of Florida is bigger than England.", 
     "Some penguins can leap 2-3 meters out of the water.", 
     "On average, it takes 66 days to form a new habit.", 
     "Mammoths still walked the Earth when the Great Pyramid was being built." 
    ] 

    func randomFact() -> String { 
     let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: facts.count) 
     return facts[randomNumber] 
    } 
} 
+0

您的設置只有10個元素寬。所以你應該期望一些重複最終發生 – Machavity

+1

請看看「相關」的問題,如http://stackoverflow.com/questions/27541145/how-to-generate-a-random-number-in-swift -with-repeated-the-before-random-n和http://stackoverflow.com/questions/26457632/how-to-generate-random-numbers-without-repetition-in-swift。 - 當然http://stackoverflow.com/questions/24026510/how-do-i-shuffle-an-array-in-swift –

+0

@Machavity是無關緊要的。我需要他們洗牌,而不是連續兩次顯示相同的報價。 – imalexdae

回答

1

可以最後隨機數或最後的事實存儲在一個變量,並檢查它在你的randomFact功能。像這樣:

var lastRandomNumber = -1 

func randomFact() -> String { 
    let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: facts.count) 

    if randomNumber == lastRandomNumber { 
     return randomFact() 
    } else { 
     lastRandomNumber = randomNumber 
     return facts[randomNumber] 
    } 
} 
+0

謝謝你的幫助Dilaver。我很感激。 – imalexdae

-1

使用arc4Random:

let max = 5 
    let f = Int(arc4random_uniform(UInt32(max))) 
    let i = Int(Float(f)) + 1; // generates # between 1 and max - 1 
相關問題