performSegueWithIdentifier:在展开Optional值

时间:2016-06-02 01:18:16

标签: ios swift null viewcontroller

我希望允许选择某一行,其中将出现如下所示的行动:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    tableView.deselectRowAtIndexPath(indexPath, animated: true)

        // Ensure controller knows which dataset to pull from,
        // so detail view is correct
        var friendChat: Friend!

        friendChat = mappedFriends[indexPath.row]

        // Now set the conditional cases: if a friend then chat, if user then friend request if not user then can invite them:
        if(friendChat.statusSort == 2) {

            var controller : IndividualChatController!

            print(friendChat.name)

            controller.friendChat? = friendChat
            controller.senderId? = Global.sharedInstance.userID
            controller.senderDisplayName? = Global.sharedInstance.userName

            self.performSegueWithIdentifier("showIndividualChat",sender: controller)

        } else
            if (friendChat.statusSort == 1) {

            print("Can invite to be friend")

        } else if (friendChat.statusSort == 0) {

            print("Invite to Feast")

        }

}

然而,在转让期间:

            controller.friendChat? = friendChat
            controller.senderId? = FeastGlobal.sharedInstance.userID
            controller.senderDisplayName? = FeastGlobal.sharedInstance.userName

错误:fatal error: unexpectedly found nil while unwrapping an Optional value出现。

为什么会发生这种情况?怎么能减轻这种情况呢?

1 个答案:

答案 0 :(得分:1)

您正在声明,但未在此处为变量controller分配值:

var controller : IndividualChatController!

通过使用感叹号将类型设置为隐式展开的可选项,即IndividualChatController!

,您承诺不是nil

但是,不保留该承诺,因为没有为其分配值,并且在此代码运行时实际上为nil:

controller.friendChat? = friendChat

这就是你得到致命错误的原因。

修复将是在声明它时为controller var赋值。例如:

var controller:IndividualChatController = IndividualChatController()