Write Less Convoluted ViewModels with Swift Subscripts

alexknows

Alex Cruz

Posted on February 15, 2024

Write Less Convoluted ViewModels with Swift Subscripts

The Swift programming language provides many convenient language features to access data immediately—for instance, the built-in subscripts for arrays and dictionaries. But what about custom Swift objects? Today, you’ll learn how to access any property without relying on dot notation.

Why Subscripts
Subscripts can be particularly useful when working with multidimensional arrays or other complex data structures, as they provide you with a clean approach to accessing elements at specific indices or by key, exactly how you would access a value from an array or dictionary.

Visualizing the Problem
Let’s assume a scenario where you have a view that switches between four states. For each state, the requirements states (no pun intended) that the corresponding data should be fetched and presented to the end user. But, the corresponding objects are encapsulated within a parent object.

You immediately reach for your switch statement:

switch state {
case .state1:    
    var object = object.correspondingObject
case .state2:
    var object = object.correspondingObject
case .state3:
    var object = object.correspondingObject
case .state4:
    var object = object.correspondingObject
}

Enter fullscreen mode Exit fullscreen mode

And you did it; you got the job done.

But you could have just done:

object[state]
Enter fullscreen mode Exit fullscreen mode

And you’re done.

Important note
The return type of your subscript method should be a protocol that the encapsulated objects conform to.

Understanding Subscripts
Subscripts can make the code more readable and concise when accessing elements in a custom data structure, such as arrays, dictionaries, or custom classes. And like in the example above, they can be used to define custom access patterns for your types, allowing you to interact with your data in a natural and intuitive way.

Summary
In this exploration, we’ve dived into subscripts, a powerful feature in Swift that allows you to provide custom access to elements in your types, improving the clarity and usability of your code.

That’s all for now, fellow developers! I hope this post has shed light on the beauty of subscripts in Swift. If you have any questions or insights to share, feel free to leave a comment below. And don’t forget to connect with me on LinkedIn and Twitter for more insights and future posts. Happy coding!

💖 💪 🙅 🚩
alexknows
Alex Cruz

Posted on February 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related