Reputation: 3977
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
Reputation: 59506
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()
.
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"
}
}
date
should contain... a Data then its type should be NSDate, not String
date
property should indicate the time when the value has been created then you can assign it = NSDate()
on the declaration of the propertycreated
is a better name for this propertyThese 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