Problem overview
The function undoLastAdd receives a shopping list, an array of strings called items, and two words, first and second. It adds first to the end, adds second to the end, then undoes the last add by removing the last item. It returns the resulting list.
With items = ["milk", "eggs"], first = "bread" and second = "jam", the list becomes ["milk", "eggs", "bread", "jam"] after the two adds. The undo removes "jam", so the result is ["milk", "eggs", "bread"].
Approach
The undo removes whatever is at the end of the array. It doesn't search for a word, so it never matters whether second also appears earlier in the list. With items = ["water"], first = "juice" and second = "water", the list goes ["water", "juice", "water"] and the undo takes off the last "water", leaving ["water", "juice"].
Since second is added and then removed, the final list is always items followed by first. The lesson still asks you to do the three operations in order, which is the point of the exercise: practising append and removeLast().
Other array methods work from the same idea. append and removeLast() both act on the end of the array, which is cheap, while insert(_:at:) and remove(at:) let you pick a position. Acting on the end is exactly how an undo button on a list behaves: the most recent change is the first one reversed.
Printing the array after each operation shows what is happening. For the first example, the list is ["milk", "eggs"] to begin with, then ["milk", "eggs", "bread"], then ["milk", "eggs", "bread", "jam"], and finally ["milk", "eggs", "bread"] again.
Step by step
- Make a mutable copy. A function's parameters are constants in Swift, so
items.append(first)on the parameter is a compile error. Declaring a newvar itemsfrom the parameter gives you an array you can change. - Append
first.appendalways adds at the end, and on an empty array the new word becomes the only item. - Append
second. Nowsecondis the last element. - Call
removeLast(). It removes the final element, which issecond. - Return the array. It ends with
first.
The solution in Swift
class Solution {
func undoLastAdd(_ items: [String], _ first: String, _ second: String) -> [String] {
var items = items
items.append(first)
items.append(second)
items.removeLast()
return items
}
}
A few Swift details matter here:
- Parameters are constants. Without the copy, the compiler rejects the code with
cannot use mutating member on immutable value: 'items' is a 'let' constant. - Shadowing.
var items = itemsdeclares a new local variable with the same name as the parameter. The right-hand side still refers to the parameter, and from the next line on,itemsmeans the copy. - Arrays are value types. Assigning an array copies it, so changing the local
itemsnever changes the array the caller passed in. After callingundoLastAdd(orig, "b", "c")onlet orig = ["a"], printingorigstill gives["a"]. removeLast()returns the removed element. The call above ignores that value, which Swift allows for this method.
Edge cases and common mistakes
- An empty list.
items = [],first = "apples",second = "pears"gives["apples"]. The array has two elements by the timeremoveLast()runs, so it never operates on an empty array. - Removing by value. Looking for
secondand removing its first match would take out the wrong"water"in the example above.removeLast()works by position. - Skipping the copy. Trying to mutate the parameter fails to compile.
- Calling
removeLast()on an empty array stops the program with a run-time error. It can't happen in this lesson, but it is why you add before you remove.
Testing
["milk", "eggs"],"bread","jam"gives["milk", "eggs", "bread"].[],"apples","pears"gives["apples"].["water"],"juice","water"gives["water", "juice"].
