Secret of Self in Swift

Anyone who study Swift programming language surely knows what keyword self means — it is reference to current object inside class instance context. Completely normal stuff in almost any objective language. The tricky part begins when one deals with static methods and properties as well as with the famous Swift's protocol-oriented paradigm. We won't emphasize attention on protocol philosophy, instead let's proceed to the most interesting part, and I'm quite sure anyone had business with it.

I'm talking about calling static method from protocol extension or defining a protocol method which must return eventual type. All of that is a particular case of late static binding, and everybody may google it anytime.

It's quite straight and simple in case of commonplace static method inside class or structure — method is easily called with type name, or you just call type(of: self) which returns current type and from that you may call static methods. However when there is no concrete type yet, but only protocol and/or its extensions (i.e. metatype), language simply won't let us do it because protocol cannot contain implementation and protocol extension is not considered as concrete code, hence we get compiler error Static member 'staticMethodName' cannot be used on protocol metatype 'ProtocolName.Protocol'.

The solution is using keyword Self (exactly that, capitalized) which is a reference to eventual type conforming to protocol. Official documentation has only one mentioning of this keyword:

In that [protocol] context, Self refers to the eventual type that conforms to the protocol.

Respectively, this keyword works only in metatype context (protocols and protocol extensions), in concrete classes or structures you get error Use of unresolved identifier 'Self'.

P.S. All of it relates to Swift versions 3 and 4, and may be changed in future. I'll try to not forget to update this article if anything changes (it might, as we all know).

Tags: programming, swift, self
Website update, astonishing! (no) (yes) (no)

Now the website has an RSS-feed, one can add it wherever you want (damn you, Google!) and read me whenever you wish (as if you couldn't before, lol).

In case your client didn't catch it by passing link to website itself (it should work, though), here is direct link to feed.

Tags: rss, website, blog, update
Leningrad in fall of 2016. Part 2. Details.

All crosswalks in SPb (as well as in the rest of Russia) are marked with zebras.

Meanwhile in Ukraine zebra is drawn only on unregulated crossroads, but crossroads with traffic lights are marked with just a dashed corridor. I was the cause of around five nearly-accidents because of it, when I (realizing my legal awareness) crossed the road, not noticing the red light. Drivers (being stopped by my inexorable hand) was too amazed with my impudence to honk.

Tags: spb, photo
More posts