Recently, I was working with Swift for a university assignment, and I was faced
with a small problem. A problem that I was able to solve using the power of the
stored properties in Swift.
My task was to develop a simple to-do list app.
When I finished my Swift App, I wasn’t satisfied with the way I was handling the tasks. It was ugly and not that flexible.
Each task, had a
defer date associated with them. Each task can be
defer up to a specific date, and therefore the app shouldn’t show
any tasks that their defer date is in the future.
My initial implementation was to have two lists of tasks, the one that has all
the tasks, regardless if the defer date is in the future or not, called
filteredTasks that I was manually maintained by adding and removing
tasks based on the defer constraint.
I had two class attributes both of them a list of
Task objects. (
definition is not important here, so think of it as a simple struct storing
task information like title, due date and defer date of the task):
1 2 var tasks = [Task]() var filteredTasks = [Task]()
Whenever I had to refresh the TableView I had to remove everything from the
filteredTasks and repopulate the
filteredTasks with the tasks from the
list, like so:
When I had to add new tasks, I needed to add the tasks in the
tasks as well
as in the
filteredTasks (if and only if the task to be added didn’t have a
And now, when the user wants to delete a task, I had two lists to maintain. So I had to remove the task from two lists as well as from the TableView.
This implementation works just fine, but is ugly, not professional and not really flexible. You have to maintain two lists when you add, remove or refresh the tasks and if I wanted to extend any new functionality probably I would have the same problem over and over.
A better solution
I was trying to find a better way to solve the problem. The solution is Computed Properties.
I refactored the code, I removed any code that maintained the
(adding, removing and updating) and I left only the
tasks list to maintain.
filteredTasks property looks like this:
Now, whenever I have to access the filtered tasks, the filtering is done on the fly
without having to maintain the
filteredTasks list myself. I just now have to
maintain the initial
tasks list and let the computed property to return the
filtered tasks for me.