无法将'Int'类型的值转换为预期的参数类型'UInt32'

时间:2016-02-22 19:56:14

标签: ios swift int arc4random uint32

关于我可以做些什么来解决这个错误的想法,我试图得到十个随机数,这样我就可以查询firebase一组包含随机数的问题。屏幕截图如下。我还添加了代码......

import UIKit
import Firebase

class QuestionViewController: UIViewController {

var amountOfQuestions = 2

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    //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
        var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1

        //The reference to your questions in firebase (this is an example from firebase itself)
        let ref = Firebase(url: "https://dinosaur-facts.firebaseio.com/dinosaurs")
        //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
                println(snapshot.key)
            })
    }    }



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func truepressed(sender: AnyObject) {
}

@IBAction func falsePressed(sender: AnyObject) {
}

enter image description here

3 个答案:

答案 0 :(得分:5)

将amountOfQuestions声明为UInt32:

var amountOfQuestions: UInt32 = 2

PS:如果你想在语法上更正,那就是数字的问题。

答案 1 :(得分:3)

amountOfQuestions变量设为UInt32而不是编译器推断的Int

var amountOfQuestions: UInt32 = 2

// ...

var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1

arc4random_uniform需要UInt32

来自Darwin docs

arc4random_uniform(u_int32_t upper_bound);

答案 2 :(得分:3)

第一件事: 方法" arc4random_uniform"期望一个类型为UInt32的参数,所以当你把那个减法放在那里时,它转换了' 1'你写信给UInt32。

第二件事:在swift中你不能从Int中减去UInt32(公式中的' 1')(在这种情况下' amountOfQuestions')。

要解决这一切,您必须考虑更改' amountOfQuestions'到:

var amountOfQuestions = UInt32(2)

应该这样做:)