HuangRunHua / wwdc23-code-notes

Example Code of WWDC23
MIT License
30 stars 5 forks source link

filtering out computed properties #3

Open mvolkmann opened 1 year ago

mvolkmann commented 1 year ago

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 commented 1 year ago

hey, thank you for sharing your idea 💡! I will check when time is available for 🧑🏻‍💻ingSent from my iPhoneOn Jun 17, 2023, at 04:27, Mark Volkmann @.***> wrote: 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.

—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you are subscribed to this thread.Message ID: @.***>