Swift Subscripts

Recently, I’ve added Swift Subscripts to my vocabulary. In many cases they feel like a reasonable amount of syntactic sugar, making my code more concise and I hope more legible. I can see where they could be overused so I’m going slow.

If you are not aware Swift allows you to declare your own subscripts to access collection members. You can always use filter, first, etc on your collection but with subscript your code may read better. 

Let’s say you have a Observable DataService with a property of Locations containing an array of places to display on a map.

@Observable class DataService {
    var locations: [Location] = []

Without subscripts you might add a method to get a specific location by searching for it’s ID:

func location(forID id: String) -> Location? {}

Then elsewhere in your code you can call that method and work with the location.

let loc = service.location(forID: id)

Subscripts provide the same function but you may prefer the simple format when using them:

let loc = service.locations[id]

It’s virtually the same thing as calling your method but I think it reads well and makes the code easier to reason with.

Assuming you want to call the subscript on the location array, the subscript for that usage might look something like this:

extension Array where Element == Location {
  subscript(id: String) -> Location? {
      self.first(where: {$0.id == id})
  }
}

Notice we placed the subscript in an extension on an array. If you define the subscript right in your DataService you would need to call it as service[id] and that may not be as clear as service.locations[id].

I try to go slowly if and when I adopt new Swift features. The curmedgeon in me thinks that so much of it just adds unnecessary complexity and often I find myself looking at recent Swift code “improvements" and thinking “thats just looks confusing” Simple, legible code is the easiest to reason with. It’s not a cleverness competition. I think judicious use of subscripts can be a “just right” amount of improved code syntax.

#iOSDev #Swift

 

Patrick McConnell @pmcconnell
🐘 Reply on Mastodon