You need to assign all the properties before you can access the @Environment
. For this reason you can't use calendar
to initialise daysForMonthView
.
A possible solution is to use onAppear
:
struct CalendarView: View {
@Environment(.calendar) private var calendar
@State private var daysForMonthView: [DateInterval] = [] // assign empty
var body: some View {
//...
.onAppear {
daysForMonthView = calendar...
}
}
}
If for some reason you need calendar
to be available in the init
, you can pass it as a parameter in init
:
struct ContentView: View {
@Environment(.calendar) private var calendar
var body: some View {
CalendarView(calendar: calendar)
}
}
struct CalendarView: View {
private let calendar: Calendar
@State private var daysForMonthView: [DateInterval]
init(calendar: Calendar) {
self.calendar = calendar
self._daysForMonthView = .init(initialValue: calendar...)
}
//...
}
Note: the downside of this approach is that a change to the calendar
will reinitialise the whole CalendarView
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…