Checklists bonus exercise Chapter 19

I was looking to see if I did this right. the exercise is in Chapter 19, page 430.

Exercise: Give ChecklistItem an init(text:) method that is used instead of the parameter-less init(). Or how about an init(text:checked:) method?

Inside of ChecklistItem.swift I added these lines:

init(text: String, checked: Bool) {
    self.text = text
    self.checked = false
    super.init()
}

Inside of ItemDetailViewController.swift I changed the done() function:

@IBAction func done() {
    if let itemToEdit = itemToEdit {
        itemToEdit.text = textField.text!
        delegate?.itemDetailViewController(self, didFinishEditing: itemToEdit)
    } else {
        // Added this line
        let item = ChecklistItem(text: textField.text!, checked: false)
        
        // Replaced these lines
        // item.text = textField.text!
        // item.checked = false
    
    delegate?.itemDetailViewController(self, didFinishAdding: item)
    }

I guess that I could also pass the false parameter as default as well? So would this be correct?

init(text: String, checked: Bool = false) {
    self.text = text
    self.checked = checked
    super.init()
}

But this don’t work “use of unresolved identifier”:

 let item = ChecklistItem(text: textField.text!, checked: checked)

The initial code looks fine to me and if it works when you run it, you know that it definitely works :slight_smile:

Yes, you can certainly have a default value for the parameter since that’s a standard Swift feature and the code you provided looks good to me. The reason you get an error for the following line:

let item = ChecklistItem(text: textField.text!, checked: checked)

Is probably because the checked variable that you pass to the initializer has not been defined anywhere. Plus, if you are initially creating an instance of ChecklistItem, wouldn’t you be using the default parameter (which is false) instead of passing a value? So that line should probably look like this:

let item = ChecklistItem(text: textField.text!)

@fahim

I think that it works as expected when setting the default in the init and when using:

let item = ChecklistItem(text: textField.text!)

Thanks for the info.

And if you want to initialize with the checked parameter set to true, then you’d call the method like this:

let item = ChecklistItem(text: textField.text!, checked: true)

This topic was automatically closed after 166 days. New replies are no longer allowed.