self. in trailing swift closures, meaning and purpose?

风格不统一 提交于 2021-01-20 08:00:32

问题


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.

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?


回答1:


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



来源:https://stackoverflow.com/questions/40665746/self-in-trailing-swift-closures-meaning-and-purpose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!