Skip to content

Iterate static members by type #1

@DanielSincere

Description

@DanielSincere

When generating allStaticMembers, include members only if they are of type Self because a programmer might want a few constants that aren't of the Self type, that shouldn't be iterated through. This will safe guard a common compilation error. Example

@StaticMemberIterable 
struct Foo {
    static let one = Foo()
    static let baseURL = "A string"

    static let allStaticMembers: [Self] = [.one]
}

should expand to

struct Foo {
    static let one = Foo()
    static let baseURL = "A string"

    static let allStaticMembers: [Self] = [.one]
}

Infer type when no matching type

Secondly, if there are no members of type Self, let the compiler infer the type. Example:

@StaticMemberIterable
enum Fixtures {
  static let fixture1: MyType = .init( /*...*/ )
  static let fixture2: MyType = .init( /*...*/ )
}

should expand to

enum Fixtures {
  static let fixture1: MyType = .init( /*...*/ )
  static let fixture2: MyType = .init( /*...*/ )

  static let allStaticMembers = [fixture1, fixture2]
}

Based on feedback from @nevillco

Looks great! For what it's worth, because I was just working on a similar macro & saw this, I think your StaticMemberIterable will include any static member, even if it's not the right type:

@StaticMemberIterable struct Foo {
    static let one = Foo()
    static let two = "A string"

    // Generates (but won't compile)
    static let allValues: [Self] = [.one, .two]
}

I added something (though verbose) to mine to check that the type is Self, here

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