1

I'm trying to figure out why I keep getting the following error using SwiftUI:

Cannot use instance member 'selectedWateredDate' within property initializer; property initializers run before 'self' is available

for my "dateInterval" variable.

@State private var selectedWateredDate = Date()
@State private var waterMeAgainIn: Date = Date().addingTimeInterval(7 * 86400)


let dateInterval = DateInterval(start: selectedWateredDate, end: waterMeAgainIn)
pkamb
  • 33,281
  • 23
  • 160
  • 191
izzieyo20
  • 13
  • 3

1 Answers1

0

Change the let property to a computed variable.

var dateInterval : DateInterval { DateInterval(start: selectedWateredDate, end: waterMeAgainIn)}
lorem ipsum
  • 21,175
  • 5
  • 24
  • 48
  • @izzieyo20 Not related to your question but note that not every day has 24 hours. If you need to add a week to a date you should use Calendar method `func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = false) -> Date?` in your case `Calendar.current.date(byAdding: .weekOfYear, value: 1, to: Date())` – Leo Dabus Jun 01 '22 at 21:31
  • @izzieyo20 if I answered your question can you please mark it as an answer with the green check mark above. – lorem ipsum Jun 01 '22 at 21:44
  • Thanks, friends! Got a lot to learn. Dates are hard... – izzieyo20 Jun 01 '22 at 21:51