Jonas Jonas - 7 months ago 13
Swift Question

Initializing a date within custom class results in error: "instance member cannot be used on type"

I found a few other questions, but none of the solutions worked, maybe my case is different in some critical aspect. Here's the code:

class ToDoList {

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day , .Month , .Year], fromDate: date)

let dateCreated : Int = components.year*10_000 + components.month*100 + components.day //TD: take YYYYMMDD from NSDate each initialization
...
}


XCode Error:


"Instance member 'calendar' cannot be used on type 'ToDoList'.


I have tried implementing components as a variable with a getter instead, to no avail.

Thanks!

Answer

Implement init function like this

class ToDoList {
    init(){
        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([.Day , .Month , .Year], fromDate: date)

        let dateCreated : Int = components.year*10_000 + components.month*100 + components.day  //TD: take YYYYMMDD from NSDate each initialization }
        // do other stuff .....
  }

}