SwiftyLab / MetaCodable

Supercharge Swift's Codable implementations with macros meta-programming.
https://swiftpackageindex.com/SwiftyLab/MetaCodable/main/documentation/metacodable
MIT License
629 stars 23 forks source link

Extend the `Default` attribute to support multiple bindings declarations with parameter packs. #75

Open SouHanaQiao opened 7 months ago

SouHanaQiao commented 7 months ago

1. Extend the Default attribute by parameter packs like this:

@attached(peer)
@available(swift 5.9)
public macro Default<each T>(_ defaults: repeat each T) =
    #externalMacro(module: "MacroPlugin", type: "Default")

So we can set default values ​​for multiple bindings variables.

Example:

struct Student {
    @Default("Simon", 22, 99)
    let name: String, age: Int, grade: Int

    enum Gender: Codable {
        case male
        case female
    }
    @Default(Gender.female, 13)
    let gender: Gender, `class`: Int
}

Equivalent to:

struct Student {
    @Default("Simon")
    let name: String
    @Default(22)
    let age: Int
    @Default(99)
    let grade: Int

    enum Gender: Codable {
        case male
        case female
    }

    @Default(Gender.female)
    let gender: Gender
    @Default(13)
    let `class`: Int
}

2. Default attribute parameter number diagnostics.

  1. Some default value parameters are missing:
    
    struct SomeCodable1 {
     @Default()       /// @Default missing default value for variable 'one'
     let one: String
    }

struct SomeCodable2 { @Default("hello") /// @Default missing default values for variables 'tow', 'three' let one: String, tow: Int, three: Float }

   2. Too many default value parameters:
```Swift
struct SomeCodable1 {
    @Default("hello", 10) /// @Default expect 1 default value but found 2 !
    let one: String
}

struct SomeCodable2 {
    @Default("hello", 10, 1, 2, 3) /// @Default expect 2 default values but found 5 !
    let one: String, tow: Int
}