SwiftUI #Preview with Callback Closure

I have created a simple calendar framework of my own. The screenshot below shows what it looks like.

The following lines show a concise version of my calendar framework. The deal is such that the app will return a date when I tap a date button with the callBack closure.

import SwiftUI

struct ContentView: View {
	@State private var navigateToAddDate = false
	@State private var days: [Day] = []
	@State var callBack: ((Date) -> Void)
	private let cols = [
		GridItem(.flexible()),
		GridItem(.flexible()),
		GridItem(.flexible()),
		GridItem(.flexible()),
		GridItem(.flexible()),
		GridItem(.flexible()),
		GridItem(.flexible())
	]
	
	var body: some View {
		NavigationStack {
			VStack {
				LazyVGrid(columns: cols) {
					ForEach(days, id: \.self) { day in
						Button(action: {
							selectedDay = day
							navigateToAddDate.toggle()
						}, label: {
							Image(systemName: "\(day.num).circle.fill")
								.resizable()
								.aspectRatio(contentMode: .fit)
								.foregroundColor(day.show ? dateTextForecolor(day: day) : .clear)
						})
						.disabled(day.isInvalid)
					}
				}
			}
		}
	}
}

struct ContentView_Previews: PreviewProvider {
	static var callBack: (Date) -> Void = { _ in }
	static var previews: some View {
		ContentView(callBack: callBack)
	}
}

struct Day: Hashable {
	let date: Date
	let text: String
	let num: Int
	let dayOfWeek: Int
	let show: Bool
	let isInvalid: Bool
}

Well, PreviewProvider works. Now, I want to use #Preview that comes with iPhone 15.

#Preview {
	var callBack: (Date) -> Void = { _ in }
	ContentView(callBack: callBack)
}

And I get a warning and an error. The warning is the following

Result of 'ContentView' initializer is unused

, which seems to stem from the said warning. How can I make the Preview guy work? Thanks.

Answered by jlilest in 773063022

You need to return the view.

#Preview {
	var callBack: (Date) -> Void = { _ in }
	return ContentView(callBack: callBack)
}

In order to make a framework, I'm choosing to make the CallBack closure not optional.

I guess it has to be optional. Ugghhhh...

Accepted Answer

You need to return the view.

#Preview {
	var callBack: (Date) -> Void = { _ in }
	return ContentView(callBack: callBack)
}
SwiftUI #Preview with Callback Closure
 
 
Q