Self-as-initializer bug?

The following compiles without error:

class A: NSObject {
    let a = self
}

but only if A inherits from NSObject. According to Xcode, the type of a is (A) -> () -> A.

Is this a known bug?

Looks like self here is the identity method -[NSObject self], which is definitely surprising, but technically not a bug, I would say. (This is why you only see this when inheriting from NSObject — normally there isn’t a named self.self method.)

Although you do often have this nice self chain available:

class A {
    init() {
        print(self.self.self.self)
    }
}

A()
1 Like

So it's a closure, but is (A) -> () -> A the correct type for it?

For that matter, why isn't self interpreted as a keyword here? After all, this:

class A: NSObject {
    let a = class
}

won't compile, but this:

class A: NSObject {
    let a = `class`
}

does refer to the -[NSObject class] method.

Oh well, perhaps it's better not to ask.

I suspect this: [Parse] Enable self rebinding (to self) by dduan · Pull Request #15306 · apple/swift · GitHub

1 Like

I'd agree that does seem to be a bug: naked self should require backticks if it's being parsed as a reference to a member.