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: https://github.com/apple/swift/pull/15306

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.

Terms of Service

Privacy Policy

Cookie Policy