得到错误“变量在其自身的初始值中使用”

时间:2015-06-30 13:05:14

标签: ios swift

当我尝试运行此代码时,我收到错误“变量在其自身的初始值中使用”。是什么导致这个错误?

var pagetitle = ""
var alertActionButtons = [UIAlertAction]()
var okAction = UIAlertAction(title: pagetitle, style: .Default) { action in
    self.presentingViewController!.dismissViewControllerAnimated(false) {
        self.unitDetailProtocolVar!.closeUnitDetail()
    }
}
alertActionButtons.append(okAction)
self.alert = self.controllerUtil.customAlert(pagetitle, buttons: alertActionButtons, alertMessage: alertMessage)

2 个答案:

答案 0 :(得分:3)

错误本身意味着您正在尝试使用变量来初始化自己。

在你的情况下,它只是一个缺失的括号,导致代码未对齐。这就是你的代码的样子:

var okAction = UIAlertAction(title: pagetitle, style: .Default){ action in
    self.presentingViewController!.dismissViewControllerAnimated(false, completion: { ()->Void in
        self.unitDetailProtocolVar!.closeUnitDetail()
    })

    alertActionButtons.append(okAction)
    self.alert = self.controllerUtil.customAlert(pagetitle, buttons: alertActionButtons, alertMessage: alertMessage)
}

您可以看到此行中使用了okAction

alertActionButtons.append(okAction)

代码中缺少的括号位于传递给UIAlertAction

的闭包中
var okAction = UIAlertAction(title: pagetitle, style: .Default){ action in
    self.presentingViewController!.dismissViewControllerAnimated(false, completion: { ()->Void in
        self.unitDetailProtocolVar!.closeUnitDetail()
    })
} // <-- this is missing

alertActionButtons.append(okAction)
self.alert = self.controllerUtil.customAlert(pagetitle, buttons: alertActionButtons, alertMessage: alertMessage)

答案 1 :(得分:1)

在调用alertActionButtons.append(okAction)之前,您忘记关闭大括号。因此,它认为您正在尝试在其自己的分配区中使用okAction。

更正代码:

var pagetitle = ""
var alertActionButtons:[UIAlertAction] = [UIAlertAction]()
var okAction = UIAlertAction(title: pagetitle, style: .Default){action in
    self.presentingViewController!.dismissViewControllerAnimated(false, completion: {()->Void in
        self.unitDetailProtocolVar!.closeUnitDetail()
    });
} // <- Added missing curly brace     
alertActionButtons.append(okAction)
self.alert = self.controllerUtil.customAlert(pagetitle, buttons: alertActionButtons, alertMessage: alertMessage)