What are subscripts in Swift?

Classes, structures and enumeration can define subscripts which are shortcuts for accessing the members of collection, list or sequence.

  • You can use subscripts to set and retrieve values by index without needing separate methods for setting and retrieval.
  • You can define multiple subscripts for given type and appropriate subscript overload to be used is decided based on the type of index value passed to the subscript.
  • Subscripts can have multiple input parameters.
  • Subscripts should have a getter and may or may not contain a setter. ( They can be of read- write and read only type.)
  • Subscripts may contain any type of input parameter and provide any type of return value except in-out parameter and default parameter value.

Leave a Reply