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

Zhao Xin owenzx at gmail.com
Tue Feb 21 21:26:50 CST 2017


I think you are right on ` lifetime guaranteed to be around until the
method call completes`. But`[unowned self]` released the retain manually in
your code. Just removing `[unowned self]` part, you code will work.

Zhaoxin

On Wed, Feb 22, 2017 at 3:18 AM, Marco S Hyman via swift-users <
swift-users at swift.org> wrote:

> > 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).
>
> value is not a static/class variable.   Without an instance of Demo it
> does not exist.  This seems to work.
>
> class Demo {
>   static var value = 0
>   lazy var increment: (Int) -> Void = { [unowned self] by in
>     value += by
>     print(value)
>   }
> }
>
> _______________________________________________
> 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/b01f861c/attachment.html>


More information about the swift-users mailing list