Swift 期待申报但已经申报

Swift expecting declaration but already declared

我正在尝试创建一个警报视图,该视图在单击按钮时执行特定操作。我尝试为警报视图创建一个新的 class,但是当我尝试向警报视图控制器添加一个操作时,Xcode 告诉我它需要一个声明,尽管变量只是声明了发生错误的行上方两步。这是代码

class alerts: UIAlertController {

var alertThenGenerateNewThingController: UIAlertController = UIAlertController()

var generateNewThingOkButton = UIAlertAction (title: "OK", style: UIAlertActionStyle.Default) {
    UIAlertAction in

    println ("generate new thing action")

}

alertThenGenerateNewThingController.addAction (generateNewThingOkButton) // Here is where Xcode says it expected a declaration

func alertThenGenerateNewThing (alertTitle: String, alertMessage: String) {

    alertThenGenerateNewThingController = UIAlertController (title: alertTitle, message: alertMessage, preferredStyle: .Alert)
    self.presentViewController (alertThenGenerateNewThingController, animated: true, completion: nil)

}

}

一方面,您不能继承 UIAlertController。其次,您只能在方法、函数或全局范围内与对象属性进行交互。 运行 您计划在其中显示警报的视图控制器中的此代码:

class viewController: UIViewController {

    var alertThenGenerateNewThingController: UIAlertController = UIAlertController()

    var generateNewThingOkButton = UIAlertAction (title: "OK", style: UIAlertActionStyle.Default) {
        UIAlertAction in

        println ("generate new thing action")

    }

    override func viewDidLoad() {
        alertThenGenerateNewThingController.addAction(generateNewThingOkButton)
    }


    func alertThenGenerateNewThing (alertTitle: String, alertMessage: String) {
        alertThenGenerateNewThingController = UIAlertController (title: alertTitle, message: alertMessage, preferredStyle: .Alert)
        self.presentViewController (alertThenGenerateNewThingController, animated: true, completion: nil)

    }

}