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

Ray Fix rayfix at gmail.com
Tue Feb 21 21:36:56 CST 2017


Thanks. My comment below.

> 
> On Feb 21, 2017, at 11:18 AM, Marco S Hyman <marc at snafu.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)
>  }
> }
> 

The problem with this solution is that this changes the semantics.  I want a value for every Demo instance.

Ray



More information about the swift-users mailing list