我对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]
}
}
您的设置只有10个元素宽。所以你应该期望一些重复最终发生 – Machavity
请看看“相关”的问题,如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 –
@Machavity是无关紧要的。我需要他们洗牌,而不是连续两次显示相同的报价。 – imalexdae