2015-06-30 23 views
1

當我試圖運行此代碼時,出現錯誤「在它自己的初始值內使用的變量」。什麼導致這個錯誤?有錯誤「在它自己的初始值內使用的變量」

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) 
+0

我看到你編輯了這個問題,以包括缺少的大括號。它仍然給你同樣的錯誤?如果是這樣,請檢查遞歸方法調用。此代碼是否寫入dismissViewControllerAnimated或closeUnitDetail? – bgolson

回答

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

您在調用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) 
相關問題