自己.在尾随的快速关闭中,意义和目的是什么? [英] 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}
我看到了这个
在闭包中引用属性(任何内容)都需要明确的自我"使捕获语义明确.
Reference to property (anything) in closure requires explicitly ‘self’ to make capture semantics explicit.
这是什么意思?到底是关于什么的?我很好奇,因为我只在尾随闭包中调用的属性或函数的上下文/范围内执行此操作,所以不知道为什么我需要`self并着迷于
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
语义学"
在这里.它具有深远的意义吗?如果我理解了闭包,我会神奇地理解闭包吗?
here. Does it have some profound meaning, and will I magically understand closures if I understand this?
推荐答案
它具有深远的意义吗?如果我理解了闭包,我会神奇地理解闭包吗?
Does it have some profound meaning, and will I magically understand closures if I understand this?
不,不.也许,也许,也许.
No and no. Or perhaps, maybe and maybe.
产生这种语法要求的原因是,它实际上可能是 一个闭包,也就是说,它可能捕获并保留其引用的环境(因为您使用的是匿名函数)可能会存储一段时间.这意味着,如果您在此处引用 self
的某些属性,例如 myProperty
,则实际上是 捕获对 self的引用
.Swift要求您明确地确认这一事实(通过说出 self.myProperty
,而不仅仅是 myProperty
),以便 you 了解这是正在发生的事情.
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.
您为什么需要了解它?因为在某些情况下,您可能会以保留周期告终,或者以其他方式以意想不到的方式保存 self
的寿命.这是一种让您思考这个事实的方法.
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.
((如果已知此特定函数将不充当闭包,即将被立即执行,则不存在此类危险,Swift将 not 要求您明确说出 self
.)
(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.)
这篇关于自己.在尾随的快速关闭中,意义和目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!