为什么"self.self"会迅速编译并运行? [英] Why 'self.self' compiles and run in swift?
问题描述
昨天我在Swift中回顾了一段代码,其中包括以下内容:
Yesterday I reviewed a piece of code in Swift which included this line:
self.self.someProperty
这让我感到惊讶,因为 self 一词被保留并用作对当前实例的引用.
Which surprised me, because the word self is reserved and used as a reference to the current instance.
起初,我用其他语言检查了这种现象,但都给出了错误.这不足为奇-但是,为什么它会迅速编译并运行?
At first I checked for that phenomenon in other languages, but all gave errors. Which wasn't a surprise - but still, why in swift does it compile and run?
第二,我在互联网上搜索了此内容,但没有发现任何相关内容...
Second I searched in the internet about this and haven't found anything relevant...
修改 我是从支票上复制的:
Edit I reproduced that and from my checks:
self.someProperty//exactly the same as:
self.self.someProperty//or as:
self.self.self.self.self.someProperty
Swift文档提供了一些说明:
每个类型的实例都具有一个称为self的隐式属性,该属性与该实例本身完全相同..
哪个很好,部分有用,但是从我的角度来看还是不够的
Which is good and partly helpful, but the way I see it it's still not enough
所以我问:
- 为什么起作用?
- 这背后有什么有用的逻辑吗?
推荐答案
这是因为对象的.self
属性是该对象本身.因此,您的第二个self
不变.
It's because the .self
property of an object is that object itself. So your second self
changes nothing.
实际上,您可以无限期地扩展此游戏(或只要您有耐心就可以):
You could, in fact, extend this game indefinitely (or as long as your patience holds out):
let s = "Hello".self.self.self.self.self.self.self.self
// s is still simply "Hello"
这篇关于为什么"self.self"会迅速编译并运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!