[swift-users] lazy initialisation

Karl razielim at gmail.com
Sun Jul 10 01:42:03 CDT 2016


> On 9 Jul 2016, at 06:34, Zhao Xin <owenzx at gmail.com> wrote:
> 
> The compiler is not smart enough to treat this as you think, nor it will be designed to. According to the documents, it is the developer‘s burden ​to add @noescape or weak or unowned. So I disagree it is a bug.
> 
> Zhaoxin
> 
> On Sat, Jul 9, 2016 at 7:30 AM, Karl <razielim at gmail.com <mailto:razielim at gmail.com>> wrote:
> 
>> On 5 Jul 2016, at 03:47, Zhao Xin <owenzx at gmail.com <mailto:owenzx at gmail.com>> wrote:
>> 
>> No, it is not a bug.
>> 
>> For a closure, you have to call self explicitly unless the closure is mark as @noescape. Also, in this situation, self is not unowned, as the closure is not stored, it ran and released. Below, is a situation that you need use unowned self. Here the closure is stored in variable d instead of running and releasing.
>> 
>>     lazy var d:()->Int = { [unowned self] in
>>         return self.a*self.b
>>     }
>> 
>> Zhaoxin
> 
> In this specific case, when you are initialising from a closure, there is no need to make the capture of ‘self’ explicit and it’s totally safe for it to be unowned. You can’t invoke the closure without going through a valid instance, and that instance always owns the closure and never the other way around.
> 


I know that the compiler doesn’t do this today, but I disagree that it will never have enough information to make inferences like this. It would simply be an adaptation of ARC to Swift - you don’t have these kind of attached lazy closures in Obj-C, so there was never any need for it. They run in the context of the instance just like a getter would, so they should have the same properties as a getter (including implicit ‘self’).

In general though, I think we are moving to “property behaviours”, which may need something like this in general. You would want to use unowned references in a stored property behaviour object; any retains/releases would be unnecessary. I’m sure we’ll talk about it more when that gets further along.

Karl
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160710/7b07dedd/attachment.html>


More information about the swift-users mailing list