是否需要使用无用的 object.self.self.. 或 Class.self.self.. ? [英] Using useless object.self.self.. or Class.self.self.. is ever need?

查看:22
本文介绍了是否需要使用无用的 object.self.self.. 或 Class.self.self.. ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们写一个简单的类来解释一下:

Let's write a simple class to explain in my head :

class SomeClass {
    var happyToUsed = 10
}

并创建一个对象

let someObject = SomeClass()

并在案例 1 中使用它的属性:

and use its property for case 1:

someObject.happyToUsed  // prints 10

对于案例 2:

someObject.self.happyToUsed // prints 10

和案例 3

someObject.self.self.self.self.happyToUsed  // prints 10 compiler is still ok, even if self count 1k

我知道 case 1 和 case 2 是一样的(直接指向同一个对象).即使我使用了 SomeClass.self 而不是对象案例也会以同样的方式运作.到目前为止,我曾在一个项目中使用过案例 3.

I know case 1 and case 2 is same ( directly point the same object ). Even if I have used SomeClass.self rather than objects cases will act the same way. I ever used case 3 in a project so far.

我的问题是有我应该更喜欢的示例案例 3 还是对内存管理的负面影响?

My question is there any example case 3 which I should prefer or negative effect on memory management?

推荐答案

这是一个 Postfix Self Expression 根据 Swift 参考:

This is a Postfix Self Expression according to the Swift reference:

后缀自表达式由表达式或类型名称组成,紧跟在 .self

A postfix self expression consists of an expression or the name of a type, immediately followed by .self

第一种形式的计算结果为表达式的值.例如,x.self 的计算结果为 x.

The first form evaluates to the value of the expression. For example, x.self evaluates to x.

您可以无限期编写 .self 的事实只是此定义的副作用.由于 x.self 本身就是一个表达式,您也可以将 .self 添加到它.你可以永远这样做.

The fact that you can write .self indefinitely is just a side effect of this definition. Since x.self is an expression itself, you can add .self to it too. And you can do this forever.

这并不意味着你应该.

它们做同样的事情:

let x                         =                          10
let x = 10

希望你同意第二个读起来更好.同样,.self 通常是多余的.根据这个讨论,似乎.self 实际上只是 Objective-C 的遗产.IMO 它还使诸如身份密钥路径 (\.self) 之类的语法更有意义".

Hopefully you'd agree that the second one reads better. Similarly, .self is generally redundant. According to this discussion, it seems like .self is really just a legacy from Objective-C. IMO it also makes syntaxes like the identity key path (\.self) "make more sense".

这篇关于是否需要使用无用的 object.self.self.. 或 Class.self.self.. ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆