Swift – Access list items from Struct, Class and Enum using Subscript

Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the member elements of a collection, list, or sequence. You use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval. For example, you access elements in an Array instance as someArray[index]and elements in a Dictionary instance as someDictionary[key].

You can define multiple subscripts for a single type, and the appropriate subscript overload to use is selected based on the type of index value you pass to the subscript. Subscripts are not limited to a single dimension, and you can define subscripts with multiple input parameters to suit your custom type’s needs.

Subscripts enable you to query instances of a type by writing one or more values in square brackets after the instance name.

Example using struct
struct Pizza {
  var ingredients = ["pomodoro", "mozzarella", "funghi","prosciutto"]
  
  subscript( index:Int ) -> String {
    return ingredients[index]
  }
}

Getting a kind of pizza, different ways:

  1. Classic one (accessing ingredients via array index):
let pizza = Pizza()
pizza.ingredients[0] // pomodoro
  1. Using subscript (accessing ingredients via subscript index, direct):
let pizza = Pizza()
pizza[0] // pomodoro
Example using class
class Pizza {
  var ingredients: [String]!

  init( ingredients: [String] ) {
    self.ingredients = ingredients
  }

  subscript( index:Int ) -> String {
    return ingredients[index]
  }
}

Getting ingredients with subscript:

let ingredients = ["pomodoro", "mozzarella", "funghi","prosciutto"]

let pizza = Pizza( list:ingredients )
pizza[0] // pomodoro

or using the classic list access:

let pizza = Pizza( list:ingredients )
pizza.ingredients[0] // pomodoro

 

Using subscript with dictionaries:

struct Pizza {

  var price:[String:Any] = [
    "margherita": 4.0, 
    "diavola":4.5, 
    "capricciosa":5.0, 
    "4 Stagioni": 4.5
  ]

  subscript (key:String) -> Any {
    get {
      if let newValue = price[key] {
        return newValue
      } else {
        return 0.0
      }
    }
  }

}

getting price using subscript:

let pizzaPrice = Pizza()
pizzaPrice["diavola"] // 4.5€
pizzaPrice["qwerty"] // 0.0€

Accessing item index with subscript and generics:

(can find more info using generics here)

struct GenericData<T> {
  var data:[T]

  subscript (index:Int) -> T {
    return data[index]
  }
}

Creating generic structure and accessing items:

struct Pizza { /* [...] */ }
struct Hamburgher { /* [...] */ }

var data = GenericData(data: [
    Pizza(), 
    Hamburgher(), 
    Date().timeIntervalSinceNow, 
    "price", 
    12345
])

data[2] // 1532886556 (the timestamp)

 

Cool, right!?

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.