How to use let constant in Xcode 15 #Preview
Asked Answered
D

1

4

How can I use a let value in the new #Preview macro in Xcode 15?

Here is my code:

#Preview {
    let categories = Bundle.main.decode([Category].self, from: "Items.json")
    CategoryView(category: categories[0])
}

I have this warning message: Result of 'CategoryView' initializer is unused

If I expand the macro to see what code is generate I can observe an alert message: 'Ambiguous use of 'init(_:traits:body:)' on line 8

@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, xrOS 1.0, *)
struct $s8Pointers33_4F24814D39CCD226F01562890C575160Ll7PreviewfMf_15PreviewRegistryfMu_: DeveloperToolsSupport.PreviewRegistry {
    static let fileID: String = "Pointers/CategoryView.swift"
    static let line: Int = 33
    static let column: Int = 1

    static func makePreview() throws -> DeveloperToolsSupport.Preview {
        DeveloperToolsSupport.Preview {
            let categories = Bundle.main.decode([Category].self, from: "Items.json")
            CategoryView(category: categories[0])
        }
    }
}

Without #Preview macro my code should be

struct CategoryView_Preview: PreviewProvider {
    static var previews: some View {
        let categories = Bundle.main.decode([Category].self, from: "Items.json")
        CategoryView(category: categories[0])
    }
}

I test it, and it works fine (even in Xcode 15) Any idea to solve this problem on Xcode 15 with the new #Preview macro?

Destination answered 29/8, 2023 at 12:39 Comment(0)
C
12

Something about the let constant makes the macro grumpy; it should work if you explicitly return the View, like so:

#Preview {
    let categories = Bundle.main.decode([Category].self, from: "Items.json")
    return CategoryView(category: categories[0])
//  ^^^^^^
}
Chequer answered 13/9, 2023 at 23:48 Comment(1)
@SébastienREMY Should this answer be appropriate, would you mind marking it as accepted in order to inform the interested people that a proper answer has been found out, please? 🙏Ambi

© 2022 - 2024 — McMap. All rights reserved.