Grammar of postfix-self expression

I think it actually makes sense, though it's a bit obscure.

For historical (Objective-C**) reasons, you can add .self to pretty much any expression, and the resulting value is that same expression's value. In the informal lexical grammar of the document, postfix-expression basically represents the concept of "pretty much any expression".

([Int] is a postfix-expression because it's a primary-expression because it's a literal-expression because it's a literal type name. It isn't an array-literal. A literal array of 1 type would be [Int.self], not [Int].)

In most cases, there's no reason to add .self, but a type name literal alone isn't treated as a value. Adding .self forces it to be treated as a value, so that you can (for example) pass the type as a parameter to a function.


**In Obj-C, KVC always requires an object and a non-empty key-path to access a value. To reference the object itself, you don't have a key-path, so NSObject defined a self method, which works as key-path "self" in KVC. It looks like this works in Swift too:

let myself = self[keyPath: \.self]
4 Likes