KexAri
KexAri

Reputation: 3977

Trouble calling a method in an init

I have this:

class SomeClass {

    let title: String
    let content: String
    let date: String?

    init(title: String, content: String) {        
        self.title = title
        self.content = content
        self.date = getDateString()        
    }

    func getDateString() -> String {        
        return "A date"      
    }    
}

However I'm getting a compiler error "Use of "self" method call in getDateString() before all stored properties are initialized". Just want to set something in my init() by using a method. How do I get around this? Any pointers would be really appreciated.

Upvotes: 2

Views: 215

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59506

You cannot use self before all the stored properties have been initialised

The rule is simple and you are violating it here

self.date = getDateString()

infact this line is equivalente to

self.date = self.getDateString()

and as you can see you are using self while date has not been initialised yet.

You must init date before calling the instance method getDateString().

A class method

If you really want to call a method to initialize date it must be a class method

class SomeClass {

    let title: String
    let content: String
    let date: String?

    init(title: String, content: String) {

        self.title = title
        self.content = content
        self.date = SomeClass.getDateString()

    }

    class func getDateString() -> String {
        return "A date"
    }
}

A few improvements

  1. If then date should contain... a Data then its type should be NSDate, not String
  2. If the date property should indicate the time when the value has been created then you can assign it = NSDate() on the declaration of the property
  3. created is a better name for this property

These 3 suggestions comes from the comment of user user3441734.

This is the updated code

class SomeClass {
    let title: String
    let content: String
    let created = NSDate()

    init(title: String, content: String) {
        self.title = title
        self.content = content
    }
}

Upvotes: 1

Related Questions