Remove or Pop
Published on Dec 20, 2019Remove or Pop — SwiftMoji Entry #28
Swift provides two instance methods for removing the last element of an Array: removeLast and popLast. The methods have the same fundamental functionality except for their return types and the way they handle the edge-case of an empty Array. The former returns a non-optional Element and crashes, while the latter returns an optional Element that is nil. This slight difference within popLast makes it a cleaner solution for destructively iterating through and utilizing the Elements of an Array. For example, in the case of iterating through an Array of Strings — printing and removing each Element — a boolean expression checking the isEmpty property would be needed in the declaration of a while-loop. Then, a separate call to removeLast would need to be inserted within the scope. Whereas with popLast, a while-let loop can be used to remove and bind the optional Element in a single statement.
var 📧inbox = [
"Don't miss this weekend's sale at Bob's Pizzeria!",
"Urgent: Production Database Backup Failed",
"Wednesday Developer Meetup Reminder"
]
while let 📧 = 📧inbox.popLast() {
print(📧)
}
📧inbox.isEmpty // true
Tagged with: