Skip to content

filtering out computed properties #3

@mvolkmann

Description

@mvolkmann

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions