Page 135

23. Swift – Subscripts


Accessing the element members of a collection, sequence and a list in Classes, Structures and Enumerations are carried out with the help of subscripts. These subscripts are used to store and retrieve the values with the help of index. Array elements are accessed with the help of someArray[index] and its subsequent member elements in a Dictionary instance can be accessed as someDicitonary[key]. For a single type, subscripts can range from single to multiple declarations. We can use the appropriate subscript to overload the type of index value passed to the subscript. Subscripts also ranges from single dimension to multiple dimension according to the users requirements for their input data type declarations.

Subscript Declaration Syntax and its Usage Let's have a recap to the computed properties. Subscripts too follow the same syntax as that of computed properties. For querying type instances, subscripts are written inside a square bracket followed with the instance name. Subscript syntax follows the same syntax structure as that of 'instance method' and 'computed property' syntax. 'subscript' keyword is used for defining subscripts and the user can specify single or multiple parameters with their return types. Subscripts can have read-write or read-only properties and the instances are stored and retrieved with the help of 'getter' and 'setter' properties as that of computed properties.

Syntax subscript(index: Int) -> Int { get { // used for subscript value declarations } set(newValue) { // definitions are written here } }

Example1 struct subexample { let decrementer: Int subscript(index: Int) -> Int { return decrementer / index } 123

​Quick is really a powerful and intuitive programming language for macOS, iOS, watchOS and tvO...  


Read more
Read more
Similar to
Popular now
Just for you