5

In swift I declared a variable as

let context:LAContext = LAContext()

It throws a warning

"Initialisation of immutable value'context' was never used, consider replacing assignment to '_' or removing it.

1 Answer 1

15

It's all in the error message

value...was never used

Your variable isn't being used anywhere, so Xcode tells you that you can remove it (because having unused variables is a waste of memory). Just use your variable somewhere and the error will go away (e.g. get a value from it, print it, etc).

Of course you mean to use it somewhere right? Otherwise you wouldn't have declared it. It's just that the Xcode (especially the new one, I noticed) checks for errors immediately, so these kinds of errors appear before you can really do anything about it.

Edit: I didn't imagine that almost 7 years later people would still be commenting on a post regarding a beginner-level compiler warning, but to be more specific, yes there are some cases where you might not want to keep a variable around or where you want to discard some return value, so you don't necessarily always "mean to use it somewhere". See comments for more.

2
  • 1
    "Of course you mean to use it somewhere right?". Not necessarily. Assigning a variable has the effect of retaining the object at least until the end of the local scope, whereas underscore does not. This is useful, for instance, when writing a test for a Combine Publisher or any token-based subscription where you simply want it to live for the scope of the test. It's still worth having this warning, but just an unfortunate disadvantage nevertheless.
    – solidcell
    Feb 12, 2021 at 21:28
  • What solidcell said. I want to emphasize on keeping the variable alive. In unit test context the difference between _and a variable name may be a failed or a passed test. Feb 26, 2022 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.