wwdc23-code-notes icon indicating copy to clipboard operation
wwdc23-code-notes copied to clipboard

filtering out computed properties

Open mvolkmann opened this issue 2 years ago • 1 comments

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.

mvolkmann avatar Jun 16 '23 20:06 mvolkmann

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: @.***>

HuangRunHua avatar Jun 17 '23 01:06 HuangRunHua