swiftswift6

How to suppress false unused variable warning?


I am getting false warning about unused variables:

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

However, I cannot remove it or replace it with _ because it changes the behaviour.

Code

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

Output:

init
deinit
1
init
deinit
1
init
1
deinit

Only the case 3 is valid for my use case and the warning is wrong. How do I get rid of the wrong warning?


This also doesn't work

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

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

foo(Test())

Still

init
deinit
1

Solution

  • There is a function in the standard library for this exact purpose - withExtendedLifetime.

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