Ensuring uniqueness

As mentioned earlier, we would like to make sure that each to-do item can only be added to the list once. To ensure this behavior is implemented, add the following test to ItemManagerTests:

func test_Add_WhenItemIsAlreadyAdded_DoesNotIncreaseCount() { 
    sut.add(ToDoItem(title: "Foo")) 
  sut.add(ToDoItem(title: "Foo")) 
   

  XCTAssertEqual(sut.toDoCount, 1) 
} 

This test fails. To make the test pass, we need to check whether the item we want to add to the list is already contained in the list. Fortunately, Swift provides a method on the array type that does exactly this. Replace add(_:) with the following code:

func add(_ item: ToDoItem) {   if !toDoItems.contains(item) {     toDoItems.append(item) 
  } 
} 

Run the tests. All the tests pass, ...

Get Test-Driven iOS Development with Swift 4 - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.