[swift-users] unowned self in closure in a playground

rintaro ishizaki fs.output at gmail.com
Tue Feb 21 21:32:09 CST 2017


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



2017-02-22 3:00 GMT+09:00 Ray Fix via swift-users <swift-users at swift.org>:

> Hi,
>
> The following code crashes:
>
> class Demo {
>   var value = 0
>   lazy var increment: (Int) -> Void = { [unowned self] by in
>     self.value += by
>     print(self.value)
>   }
>  }
>
> Demo().increment(3)
> error: Playground execution aborted: error: Execution was interrupted,
> reason: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0).
>
> However if I call it this way:
>
> do {
>   let demo = Demo()
>   demo.increment(3)
> }
>
> All is well.  This breaks my mental model of lifetime guaranteed to be
> around until the method call completes.
> Is it me that is wrong or the playground.  Is the second way working just
> by luck?
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170222/7014a654/attachment.html>


More information about the swift-users mailing list