Swift 错误 "Variable used within its own initial value"

Swift Error "Variable used within its own initial value"

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

    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()

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

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

let alert = alert.buttons["OK"]

alert 从未在此行之前声明过,所以你不能这样写。

例如,以这种情况为例,

let a = a+5

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