Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

filtering out computed properties #3

Open
mvolkmann opened this issue Jun 16, 2023 · 1 comment
Open

filtering out computed properties #3

mvolkmann opened this issue Jun 16, 2023 · 1 comment

Comments

@mvolkmann
Copy link

A nice enhancement to your macro would be to filter out computed properties so the generate initializer does not contain parameters for them. For example, suppose you want to to apply your macro to this:

struct Dog: CustomStringConvertible {
    var name: String
    var breed: String

    var description: String {
        "\(name) is a \(breed)"
    }
}

I think you would want the result to be this:

@TypeInit
struct Dog: CustomStringConvertible {
    var name: String
    var breed: String

    var description: String {
        "\(name) is a \(breed)"
    }
    init(name: String, breed: String) { // no parameter for description
        self.name = name
        self.breed = breed
    }
}

I was able to achieve this with the following code in the expansion function:

        // Changed "let" to "var".
        var variableDecls = members
            .compactMap { $0.decl.as(VariableDeclSyntax.self) }

        // Remove computed properties.
        variableDecls = variableDecls.filter { decl in
            decl.bindings.first?.accessor == nil
        }

Surely there must be a better way to detect computed properties, but that is the best I could find for now.

@HuangRunHua
Copy link
Owner

HuangRunHua commented Jun 17, 2023 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants