Swift Basics - subscripts

Shortcuts to access elements in collections, lists or sequences.

Subscript of an array:
var array1 = [1, 2, 3, 4, 5, 6]
print(array1[2])

Custom subscripts:
class MyFoods
{
 private var foods = ["Ice cream", "Pizza", "Hot dog"]
 subscript(index: Int) -> String
 {
 get { return names[index]}
 set { names[index] = newValue}
}

To use it:
var myFoods = MyFoods()
print(myFoods[0])

Ready only custom subscripts:
class MyFoods
{
 private var foods = ["Ice cream", "Pizza", "Hot dog"]
 subscript(index: Int) -> String
 {
 get { return names[index]}
}
OR
class MyFoods
{
 private var foods = ["Ice cream", "Pizza", "Hot dog"]
 subscript(index: Int) -> String
 {
  return names[index]
}

You can calculate something inside a subscript:

struct AreaOfTable
{
 var length: Int
 subscript(index: Int) -> Int
 { return length * Index}
}

To use:
var myTable = AreaOfTable(length: 3)
print(myTable[3])

A subscript can be used to adjust a value:

struct WhatsUp
{
 subscript(name: String) -> String
 { return "What's Up, \(name)"}
}

var hello = WhatsUp()
print(hello("Mary"))

A structure can have more than one subscript:
struct Areas
{
  subscript(square index: Int) -> Int {return index * index}
  subscript(radius index: Int) -> Double (return index * 22/7)
}
To call:
var areaA = Areas()
print(areaA(square : 5))
print(areaA(radius: 3))

Multi dimensional subscript:

struct MultiD
{
 var numbers = [[1,2],[3,4],[5,6]]
 subscript(a: Int, b: Int) -> Int
 {
  get{return numbers[a, b]}
  set{ numbers[a][b] = newValue}
}

To call:
var md = MultiD()
md[1][0] = 8

Multiple parameters in a subscript:
struct Person
{
 subscript(food f: String, music m:String, age a: Int) -> String
{return f + " " + m}}

To call:
var mary = Person()
var foodAndMusic = mary[food: "Pizza", Music: "KPop", age: 10]


Comments

Popular posts from this blog

Setting up a playground

Go to another page