我对Swift和编程一般都是新手,所以在我试图掌握这一点时请耐心等待。
我一直在从Treehouse学习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 :(得分: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]
}
}