Sometimes, I have to keep a class instance alive without explicit named reference to it. For example, in this code, compiler complains.
let a = AAA()
// "... `b` never used" warning.
let b = a.bbb()
a.ddd(333)
But if I replace b
with _
, now the instance dies immediately and produces incorrect result.
let a = AAA()
// "... `b` never used" warning.
let _ = a.bbb()
a.ddd(333)
Same result without let
keyword.
let a = AAA()
// "... `b` never used" warning.
_ = a.bbb()
a.ddd(333)
Here's working example code to reproduce the situation.
func eee() {
final class AAA {
weak var ccc: AAA?
func bbb() -> AAA {
let r = AAA()
ccc = r
return r
}
func ddd(_ value: Int) {
// This side effect is what I want.
print(value)
ccc?.ddd(value)
}
}
let a = AAA()
// "... `b` never used" warning.
let b = a.bbb()
a.ddd(333)
_ = b
}
eee()
How to suppress the warning with keeping the instance alive?
I'm using Swift 4.1 included in Xcode 10.0.
This code is just a short example to show the situation. Content of this class is not really important. I just want to show the case that an object is required to alive without explicit reference to it.
If you're confused with my intention, I'm sorry. There's no intention in the code except showing the problem. I renamed everything to erase meanings.
One way:
let a = Pipe1()
let b = a.extend()
a.push(333)
_ = b
Another way:
let a = Pipe1()
withExtendedLifetime(a.extend()) {
a.push(333)
}
But I cannot understand or guess what you really want to do with your code...