To be able to use a short initializer only setting the title, we need to define it ourselves. But this also introduces a new source of potential bugs. We can remove the two micro features we have implemented and still have both tests pass. To take a look at how this works, open ToDoItem.swift, and comment out the properties and assignment in the initializer:
struct ToDoItem { // let title: String // let itemDescription: String? init(title: String,
itemDescription: String? = nil) {
// self.title = title // self.itemDescription = itemDescription } }
Run the tests. Both tests still pass. The reason for this is that they do not check whether the values of the initializer arguments are actually set to any ToDoItem properties. We can easily extend the tests to make sure that the values are set. First, let's change the name of the first test to test_Init_WhenGivenTitle_SetsTitle(), and replace its contents with the following code:
let item = ToDoItem(title: "Foo") XCTAssertEqual(item.title, "Foo",
"should set title")
This test does not compile because ToDoItem does not have a title property (it is commented out). This shows that the test is now testing our intention. Remove the comment signs for the title property and assignment of the title in the initializer, and run the tests again. All the tests pass. Now, replace the second test with this one:
func test_Init_WhenGivenDescription_SetsDescription() { let item = ToDoItem(title: "",
itemDescription: "Bar") XCTAssertEqual(item.itemDescription, "Bar", "should set itemDescription") }
Remove the remaining comment signs in ToDoItem, and run the tests again. Both the tests pass again, and they now actually test that the initializer works.