Swift Optionals - 在解开可选值时意外地发现nil

mfo*_*est 2 ios parse-platform swift

我是Swift的新手,并且一直试图围绕可选值包围(ha)我的脑袋.据我所知 - 尽管我可能错了 - 变量可以是可选的,因此包含一个nil值,这些必须在代码中考虑.

每当我点击我的应用程序中的"保存"按钮时,我都会收到错误:'致命错误:在展开可选值时意外发现nil'.

@IBAction func saveTapped(sender: AnyObject) {

    //code to save fillup to Parse backend

    // if variable is not nil
    if let username = PFUser.currentUser()?.username {

        // set username equal to current user
        self.object.username = username

    }else{

        println("PFUser.currentUser()?.username contained a nil value.")

    }

    // if variable is not nil
    if let amount = self.amountTextField.text {

        //set amount equal to value in amountTextField
        self.object.amount = self.amountTextField.text

    }else{

        println("self.amountTextField.text contained a nil value.")

    }

    // if variable is not nil
    if let cost = self.costTextField.text {

        // set cost equal to the value in costTextField
        self.object.cost = self.costTextField.text

    }else{

        println("self.costTextField.text contained a nil value.")

    }

    // set date equal to the current date
    self.object.date = self.date

    //save the object
    self.object.saveEventually { (success, error) -> Void in

        if error == nil {

            println("Object saved!")

        }else{

            println(error?.userInfo)

        }


    }

    // unwind back to root view controller
    self.navigationController?.popToRootViewControllerAnimated(true)

}
Run Code Online (Sandbox Code Playgroud)

不确定错误是否是由于此代码块或其他地方的某些内容 - 如果需要可以提供主类代码.

任何人都能提供的任何帮助都会非常感激,因为这一直困扰着我一段时间.

Fra*_*kie 5

从你的代码和评论听起来你的问题肯定是 self.object

您的代码从不使用if let语句来检查以确保self.object不是nil

使用println(username)作品,因为你username不是零.但是当你试图打电话时self.object.username,self.object就是导致崩溃的原因.

你可能在你的实现中有一个属性,就像var object:CustomPFObject!这意味着,第一次访问这个变量时,它预计不会是零.您可能想要检查第一次设置self.object的代码,并确保在您尝试访问它之前设置它.

如果你无法管理何时self.object设置,何时访问它,那么将你的声明更改为var object:CustomPFObject? Now它是可选的,当你编写代码时,你将被迫做出决定.

例如:

var object:CustomPFObject?

let text = self.object.username //won't compile

let text = self.object!.username //mighty crash

let text = self.object?.username //you're safe, 'text' just ends up nil
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助您解决问题.