【发布时间】:2016-02-22 21:52:07
【问题描述】:
我正在使用arc4random 生成 10 个随机数,因此我可以查询 firebase 以获取包含随机生成的数字的问题。问题是我不希望任何数字出现不止一次,所以没有重复的问题。当前代码如下...
import UIKit
import Firebase
class QuestionViewController: UIViewController {
var amountOfQuestions: UInt32 = 40
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Use a for loop to get 10 questions
for _ in 1...10{
// generate a random number between 1 and the amount of questions you have
let randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1
print(randomNumber)
// The reference to your questions in firebase (this is an example from firebase itself)
let ref = Firebase(url: "https://test.firebaseio.com/questions")
// Order the questions on their value and get the one that has the random value
ref.queryOrderedByChild("value").queryEqualToValue(randomNumber)
.observeEventType(.ChildAdded, withBlock: {
snapshot in
// Do something with the question
print(snapshot.key)
})
}
}
@IBAction func truepressed(sender: AnyObject) {
}
@IBAction func falsePressed(sender: AnyObject) {
}
}
【问题讨论】:
-
你不应该从 amountOfQuestions 中减去 1
-
如果您不希望它们出现两次,您可以从原始数组中随机删除每个元素
标签: ios swift random firebase arc4random