Swift Tutorial - Tutorialspoint

(backadmin) #1

When we run the above program using playground, we get the following result:


Sunday
Monday
Tuesday
Wednesday

Options in Subscript


Subscripts takes single to multiple input parameters and these input parameters also
belong to any datatype. They can also use variable and variadic parameters. Subscripts
cannot provide default parameter values or use any in-out parameters.


Defining multiple subscripts are termed as 'subscript overloading' where a class or
structure can provide multiple subscript definitions as required. These multiple subscripts
are inferred based on the types of values that are declared within the subscript braces.


struct Matrix {
let rows: Int, columns: Int
var print: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
print = Array(count: rows * columns, repeatedValue: 0.0)
}
subscript(row: Int, column: Int) - > Double {
get {
return print[(row * columns) + column]
}
set {
print[(row * columns) + column] = newValue
}
}
}
var mat = Matrix(rows: 3 , columns: 3 )

mat[ 0 , 0 ] = 1.0
mat[ 0 , 1 ] = 2.0
mat[ 1 , 0 ] = 3. 0
mat[ 1 , 1 ] = 5.0
Free download pdf