Subscripts in Swift ?

Shortest way to access the member elements of collection, list or sequence, means there is no need to create saparate function. lets say you have an array so you can write subscripts for setting and retrieving the value by index. Sounds good ???

Another good thing is we can define number of subscripts based on the type of index value we pass, even we can define subscripts with multiple input parameters, so its all to our need.

The syntax is very much similar to stored property and functions. Just we need to write subscript keyword and specify one or more input paramters and reture type. like the methods subscripts are also read-write or readonly. This behaviour is communicated by the same way we do in computed properties. 

subscript(index: Int) -> Int    {
    get {
        //return value here
    } set(newValue) {
        //set the new value here
    }
}

the usage is to access the member elements in a collection, list or sequence. For example, Swift’s Dictionary instance. You can set and get the value using Key. if they key does’t exist it will add into the Dictionary.

var priorities = ["Work" : 3, "Family" : 1, "Other" : 4]
priorities["Work"] = 2

Swift’s Dictionary type implements its key-value subscripting, its takes and returns an optional value. if you set the value as nil it’ll remove from Dictionary.

priorities["Work"] = nil

the interseting part what i like is subscripts can take any types of values, n number of value and can return any type of value, but they can’t use in-out parameters and can’t provide default parameters value.

struct Matrix {
    let rows: Int, columns : Int
    var grid : [Double]

    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(repeating: 0.0, count: rows * columns)
    }

    private func isValidIndex(row: Int, column: Int) -> Bool    {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }  

    subscript (row: Int, column: Int) -> Double  {
        get {
            assert(isValidIndex(row: row, column: column))
            return grid[(row * column) + column]
        } set {
            assert(isValidIndex(row: row, column: column))
            grid[(row * column) + column] = newValue
        }
    }
}

var matrix = Matrix(rows: 2, columns: 2)
matrix[1, 1] = 10.0

print(matrix[1, 1])

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s