You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift单元测试本地运行通过 但AppCenter报变量在自身初始化时被使用错误

触发原因

这个报错是Swift编译器的版本差异导致的:

  • 你本地使用的是更高版本的Xcode(对应更高版本的Swift编译器),已经修复了闭包捕获的误判问题,所以本地编译运行正常。
  • AppCenter的构建环境使用的是更低版本的Xcode,该版本的Swift编译器存在已知bug,会错误判断你代码中定义的process闭包在初始化时引用了自身,因此抛出*Variable used within its own initial value*的编译错误。

可行解决方案

你可以任选以下一种方案修复:

方案1:修改闭包定义方式,规避编译器误判

两种修改方式任选其一即可:

  1. 拆分为声明、赋值两步:
func test_entering_text_delays_processing_until_settled() {
    let expect = expectation(description: "processing completed")
    
    var finalString: String = ""
    var timesCalled: Int = 0
    
    // 先声明类型,再赋值
    var process: (String) -> ()!
    process = {
        finalString = $0
        timesCalled += 1
        expect.fulfill()
    }

    Debounce<String>.input("A", comparedAgainst: "AB", perform: process)
    Debounce<String>.input("AB", comparedAgainst: "ABCD", perform: process)
    Debounce<String>.input("ABCD", comparedAgainst: "ABC", perform: process)
    Debounce<String>.input("ABC", comparedAgainst: "ABC", perform: process)

    wait(for: [expect], timeout: 2.0)

    XCTAssertEqual(finalString, "ABC")
    XCTAssertEqual(timesCalled, 1)
}
  1. 给闭包增加显式捕获列表:
let process: (String) -> () = { [unowned expect] in
    finalString = $0
    timesCalled += 1
    expect.fulfill()
}

方案2:升级AppCenter构建环境的Xcode版本

在AppCenter的构建配置中,将使用的Xcode版本调整为和你本地开发一致的版本,即可直接消除版本差异导致的编译器bug。


内容的提问来源于stack exchange,提问作者Leon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:54:03