Skip to content

swift: field of type self conflicts with implicit self in initializer #1530

@lilyball

Description

@lilyball

When generating Swift code where an object has a field named self, this synthesizes code that looks like

public struct Foo: GraphQLSelectionSet {
    // …
    public init(`self`: `Self`? = nil) {
        self.init(unsafeResultMap: ["__typename": "Foo", "self": `self`.flatMap {  }])
    }
    // …
}

Unfortunately, while the escaping makes this syntactically correct, the parameter `self` conflicts with the implicit parameter self because, while self is indeed a keyword, the compiler also treats it as equivalent to the identifier.

The use of the synthesized variable public var `self`: `Self` is perfectly fine as it doesn't actually reference the identifier within itself, and AFAICT no other generated code in the type references the self var (if it did, self.`self` would work fine of course). So we really just need to fix the initializer.

I'm pretty sure self is the only token we have to treat specially here, and I'm tempted to just name it _self, although of course if there's another field explicitly named _self then it would conflict; maybe we can detect that and tack on trailing underscores until we find something unique, e.g. _self_, _self__, etc. In any case, this change wouldn't be visible outside of the function as long as we keep the external parameter name as `self`. With the proposed fix the above type would become

public struct Foo: GraphQLSelectionSet {
    // …
    public init(`self` _self: `Self`? = nil) {
        self.init(unsafeResultMap: ["__typename": "Foo", "self": _self.flatMap {  }])
    }
    // …
}

CC @designatednerd

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions