KexAri
KexAri

Reputation: 3977

Do I need a convenience initializer here?

New to swift. In my class I have my main initializer (designated) like so:

init(name: String, location: String, image: UIImage) {

        self.name = name
        self.location = location
        self.image = image
        postDate = NSDate()
        dateString = getDateString()

    }

I then have another initializer below it that actually passes the two date objects into the parameters instead of creating them:

  init(name: String, location: String, date: NSDate, dateString: String, image: UIImage) {

        self.name = name
        self.location = location
        self.image = image
        postDate = date
        self.dateString = dateString


    }

Do I need to make this a convenience initializer? If I make it into a convenience I know I have to put the word convenience before it, but why bother? Does this have any advantages?

Upvotes: 1

Views: 46

Answers (1)

Diego Freniche
Diego Freniche

Reputation: 5414

In your class you're basically copying & pasting in every single initializer. This is a bad practice, because sometimes you'll forget to init some property (if it's optional). And also all this duplicated code is a clear code smell: it's harder to maintain. If you need to change something, change it in 7 init methods...

So here's where convenience inits help you. The main idea is that you have a designated init, the one with the longest list of parameters (this is the one most concrete, as you have the most data to create your object). If you need to call super, do it from inside this designated init.

All other inits have less data to create the object, so they're more general. Call the designated init from these "convenience" inits passing in default values.

class Test1 {

    var name: String
    var location: String
    var image: UIImage
    var postDate: NSDate
    var dateString: String

    convenience init(name: String, location: String, image: UIImage) {
        self.init(name: name, location: location, date: NSDate(), dateString: "", image: image)
    }

    init(name: String, location: String, date: NSDate, dateString: String, image: UIImage) {

        self.name = name
        self.location = location
        self.image = image
        postDate = date
        self.dateString = dateString
    }
}

ALSO: you shouldn't call functions / methods inside your inits. self isn't yet fully initialized.

Upvotes: 5

Related Questions