-3

I am trying to create a 3 or 4 digit integer variable based on the date. So, if the date were March 4th, the number would be 304, and if the date were November 11th, the number would be 1111. However, whenever I try to do it I receive the error on the last line of code: "Cannot use instance member 'month' within property initializer; property initializers run before 'self' is available". How do I fix this?

let day = Calendar.current.component(.day, from: Date())
let month = Calendar.current.component(.month, from: Date())
var todaysDate = month*100+day
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 1
    Please provide more context of the code – Inder Kumar Rathore Mar 19 '19 at 15:34
  • 1
    Please [search on the error](https://stackoverflow.com/search?q=%5Bswift%5D+Cannot+use+instance+member++within+property+initializer%3B+property+initializers+run+before+%27self%27+is+available) before posting. This has been asked and answered many times before. – rmaddy Mar 19 '19 at 15:40

1 Answers1

0

You need to do something like below, right now swift compiler doesn't allow this. May be in future it will be more intelligent do the heavy lifting.

class ABC {
    let day = Calendar.current.component(.day, from: Date())
    let month = Calendar.current.component(.month, from: Date())
    var todaysDate: Int

    init() {
        todaysDate = month*100+day
    }
}
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184