Confused Confused - 16 days ago 5
Swift Question

self. in trailing swift closures, meaning and purpose?

whenever I use a trailing closure on an action ... example:

run(SKAction.wait(forDuration: 10)){timeRemains = false}


I’m seeing this:


Reference to property (anything) in closure requires explicitly ‘self’
to make capture semantics explicit.


enter image description here

What does this mean? And what is it on about? I'm curious because I'm only ever doing this in the context/scope of the property or function I want to call in the trailing closure, so don't know why I need `self and fascinated by the use of the word


"semantics"


here. Does it have some profound meaning, and will I magically understand closures if I understand this?

Answer

Does it have some profound meaning, and will I magically understand closures if I understand this?

No and no. Or perhaps, maybe and maybe.

The reason for this syntactical demand is that this might really be a closure, that is, it might capture and preserve its referenced environment (because the anonymous function you are passing might be stored somewhere for a while). That means that if you refer here to some property of self, such as myProperty, you are in fact capturing a reference to self. Swift demands that you acknowledge this fact explicitly (by saying self.myProperty, not merely myProperty) so that you understand that this is what's happening.

Why do you need to understand it? Because under some circumstances you can end up with a retain cycle, or in some other way preserving the life of self in ways that you didn't expect. This is a way of getting you to think about that fact.

(If it is known that this particular function will not act as a closure, i.e. that it will be executed immediately, then there is no such danger and Swift will not demand that you say self explicitly.)

Comments