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

如何消除Swift中误报的未使用变量警告?

如何消除Swift中未使用变量的误报警告?

我碰到了一个未使用变量的误报警告:

warning: initialization of immutable value 'push' was never used; consider replacing with assignment to '' or removing it

但我不能移除这个变量,也不能把它换成_——这么做会改变程序的行为。

代码示例

struct Test : ~Copyable { 
    init() { print("init") } 
    deinit { print("deinit") } 
}

// case 1
do {
    _ = Test()
    print(1)
}

// case 2
do {
    let _ = Test()
    print(1)
}

// case 3
do {
    let _test = Test() 
    print(1)
}

输出结果

init
deinit
1
init
deinit
1
init
1
deinit

只有案例3符合我的需求,但它会触发那个误报警告。我试过下面的方法,也达不到预期效果:

struct Test : ~Copyable {
    init() { print("init") }
    deinit { print("deinit") }
}

func foo(_: consuming Test) {
    print(1)
}

foo(Test())

尝试后的输出

init
deinit
1

可行的解决办法

用Swift标准库的withExtendedLifetime(_:_:)函数就行,它能把对象的生命周期延长到闭包执行结束,还不会触发未使用变量的警告:

struct Test : ~Copyable { 
    init() { print("init") } 
    deinit { print("deinit") } 
}

do {
    withExtendedLifetime(Test()) {
        print(1)
    }
}

修正后的输出

init
1
deinit

另外,也可以给变量加@_unused属性(注意这是私有属性,未来版本可能变动),或者加一行_ = _test显式“使用”变量来消警告,但withExtendedLifetime是更标准的做法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:41:00