Why 'self.self' compiles and run in swift?

倖福魔咒の 提交于 2019-12-22 06:36:53

问题


Yesterday I reviewed a piece of code in Swift which included this line:

self.self.someProperty

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 documentation gives some sort of explanation:

Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself.

Which is good and partly helpful, but the way I see it it's still not enough

So I'm asking:

  1. Why does it work?
  2. Is there any useful logic behind this?

回答1:


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"



回答2:


Yup, no matter how many .self's you have after a string, it's still just itself



来源:https://stackoverflow.com/questions/34499890/why-self-self-compiles-and-run-in-swift

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