Adding an itemDescription property

A to-do item can have a description. We would like to have an initializer that also takes a description string. To drive the implementation, we need a failing test for the existence of this initializer:

func test_Init_TakesTitleAndDescription() { 
  _ = ToDoItem(title: "Foo", 
itemDescription: "Bar") }

Again, this code does not compile because there is Extra argument 'itemDescription' in call. To make this test pass, we add an itemDescription property of type String? to ToDoItem:

struct ToDoItem { 
  let title: String 
  let itemDescription: String? 
} 

Run the tests. The test_Init_TakesTitle() test fails (that is, it does not compile) because there is Missing argument for parameter 'itemDescription' in the call. The reason for this is that we use a feature of Swift where structs have an automatic initializer with arguments defining their properties. The initializer in the first test only has one argument, and therefore, the test fails. To make the two tests pass again, we need to add an initializer that can take a variable number of parameters. Swift functions (and init methods as well) can have default values for parameters. You will use this feature to set itemDescription to nil if there is no parameter for it in the initializer.

Add the following code to ToDoItem:

init(title: String, 
itemDescription: String? = nil) {

self.title = title self.itemDescription = itemDescription }

This initializer has two arguments. The second argument has a default value, so we do not need to provide both arguments. When the second argument is omitted, the default value is used.

Now, run the tests to make sure that both tests pass.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.95.150