Swift 错误“变量在其自身的初始值内使用”

Bil*_*oyo 1 xcode ios swift xcode-ui-testing

我正在为我的应用程序编写 XCUITest。我声明警报是为了waitForExpectationsWithTimeout使我的测试异步......但是它在第 5 行Variable used within its own initial value的声明中抛出错误alert

    let timeout = NSTimeInterval()
    let app = XCUIApplication()

    let exists = NSPredicate(format: "exists == 1")
    let alert = alert.buttons["OK"]


    testCase.addUIInterruptionMonitorWithDescription("Enable Notifications") { (alert) -> Bool in
            alert.buttons["OK"].tap()
        return true
    }

    self.buttons["Enable notifications"].tap()
    testCase.expectationForPredicate(exists, evaluatedWithObject: alert, handler: nil)
    testCase.waitForExpectationsWithTimeout(timeout, handler: nil)
    app.tap()
Run Code Online (Sandbox Code Playgroud)

有人能告诉我为什么它会抛出这个错误以及我能做些什么来解决这个问题。提前致谢。

Aak*_*ash 5

这是因为在您的行中没有。5、你写了

let alert = alert.buttons["OK"]
Run Code Online (Sandbox Code Playgroud)

在此行之前从未声明过警报,因此您不能编写此内容。

以这个案例为例,

let a = a+5
Run Code Online (Sandbox Code Playgroud)

现在编译器会抛出同样的错误,因为它不知道 'a' 的值,因为它之前没有声明。