[swift-users] unowned self in closure in a playground
rintaro ishizaki
fs.output at gmail.com
Tue Feb 21 22:10:09 CST 2017
2017-02-22 12:53 GMT+09:00 Ray Fix <rayfix at gmail.com>:
>
> On Feb 21, 2017, at 7:32 PM, rintaro ishizaki <fs.output at gmail.com> wrote:
>
> lifetime guaranteed to be around until the method call completes
>
>
> AFAIK, this is true.
> However, in this case, it's not a method call. The lifetime is only
> guaranteed until getter:increment completes.
>
> Demo().increment(3)
> |--------------| lifetime
>
>
> Thanks! This is an interesting explanation.
>
> It is curious that naming the variable cases different behavior.
> IOW, this doesn’t have a problem:
>
> let demo = Demo()
> demo.increment(3)
>
> Lifetime seems to last the entire expression.
>
>
I'm not sure, but I think the compiler is just lazy enough to release the "
demo" value *after* the entire expression or scope finishes.
Again, I'm not sure. :)
Anyway, If I were you, I would define a wrapper method:
class Demo {
var value = 0
lazy var _increment: (Int) -> Void { [unowned self] by in ... }
func increment(by: Int) {
_increment(by)
}
}
Demo().increment(by: 3)
> Ray
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170222/e78085f7/attachment.html>
More information about the swift-users
mailing list