Subscript

“subscript” used in Swift as an indexer , It is a mechanism to access a chained data such as a custom list by index , here is an example of what we can do with subscript


class Person{

    var job:[String]

    

    subscript(index:Int)->(String) {

        get{

            return self.job[index]

        }

        set{

            self.job[index]=newValue

        }

    }

    func getJob()->String{

    return "job"

    }

    init(profession:[String]){

        job = profession

    }

}

 

var jobs=["engineer","physician","shop keeper"]

var p=Person(profession: jobs)

print(p[1])//access mList by index = 1


subscript is particularly useful when dealing with custom list , suppose we keep a person’s Record as:

class Record{

    var name:String

    var age:Int

    init(name:String,age:Int){

        self.name = name

        self.age = age

    }

}

And then we have  a list of such a Records as:

class MyList{

    var data:[Record]

    subscript(index:Int)->Record{

        get{

            return data[index]

        }

        set{

            data[index] = newValue

        }

    }

    init(list:[Record]){

        self.data = list

    }

}

let record1 = Record(name: "Smith", age: 23)

let record2 = Record(name: "Bob", age: 46)

let record3 = Record(name: "Kent", age: 66)

let mList = MyList(list: [record1,record2,record3])

let rec = mList[2]//access mList by index = 2

print("\(rec.age)")




 © Xosrov 2016