iosswiftuimacros

Does @attached macros work in the preview body?


I have write MockBuilder macro which generates a single mock instance. Here is a DeveloperCardViewParameters which has MockBuilder macro and generation mock property.

@MockBuilder()
struct DeveloperCardViewParameters {
    let icon: Image
    let title: String
    let description: String
    #if DEBUG
    static var mock: DeveloperCardViewParameters {
        .init(
            icon: MockBuilderSupportedType.generate(elementType: .image, generatorType: .random) as! Image,
            title: MockBuilderSupportedType.generate(elementType: .string(), generatorType: .random) as! String,
            description: MockBuilderSupportedType.generate(elementType: .string(), generatorType: .random) as! String
            )
       }
    #endif
 }

here is DeveloperCardView Preview

 #if DEBUG
    #Preview(body: {
        DeveloperCardView(parameters: DeveloperCardViewParameters.mock) // This line I get error -> "Type 'DeveloperCardViewParameters' has no member 'mock'"
    })
 #endif

Does @attached macros work in the preview body?


Solution

  • Try to show a preview that way works fine. here is a explanation why #preview doesn't work

    #if DEBUG
    struct DeveloperCardView_Previews: PreviewProvider {
        static var previews: some View {
            DeveloperCardView(parameters: DeveloperCardViewParameters.mock)
        }
    }
    #endif