In general, we use subscripts when we use arrays, dictionaries (Dictionary). In fact, in Swift, we can customize subscripts for classes, structs, enumerations, and so on.
1 Basic use
structVector3 {varX:double =0.0 varY:double =0.0 varZ:double =0.0subscript (Index:int)Double? { Switch(index) { Case 0: returnx Case 1: returny Case 2: returnZdefault: returnNil}} Subscript (axis:string)Double? { Switch(axis) { Case "x","X": returnx Case "y","Y": returny Case "Z","Z": returnZdefault: returnNil}} }
We define a subscript in the struct, and this subscript is similar to a method, and it looks like it is of type Int, Double? , String-Double?. You can then use "[Index]" and "[string]" to take the value when you call.
var Ten - - )// can be evaluated by subscript vector[0] // vector[ " Z " // -
In the above code, we can only take values, but we cannot use "[index]", "[string]" to assign a value.
The subscript method above is equivalent to writing only the Get method, in which we can add a set. This allows you to assign a value using "[Index]" and "[string]".
structVector3 {varX:double =0.0 varY:double =0.0 varZ:double =0.0subscript (Index:int)Double? { Get { Switch(index) { Case 0: returnx Case 1: returny Case 2: returnZdefault: returnNil}} Set{guard Let newvalue= NewValueElse{return} Switch(index) { Case 0: x=NewValue Case 1: Y=NewValue Case 2: Z=NewValuedefault: ()}}} subscript (axis:string)Double? { Get { Switch(axis) { Case "x","X": returnx Case "y","Y": returny Case "Z","Z": returnZdefault: returnNil}} Set{guard Let newvalue= NewValueElse{return} Switch(axis) { Case "x","X": x=NewValue Case "y","Y": Y=NewValue Case "Z","Z": Z=NewValuedefault: () } } } }varVector = Vector3 (x:TenY: -Z: -) vector[0] = -Vector//x:100, y:20, z:30vector["y"] = $Vector//x:100, y:200, z:30
2 Multi-dimensional subscript
structMatrix {vardata: [[Double]] let Row:int let Col:int init (Row:int, col:int) {Self.row=Row Self.col=Col Data=[[Double]] () for_inch 0.. <Row {Let Arow= Array (repeating:0.0, Count:col) data.append (Arow)}} subscript (X:int, Y:int)-Double {Get{assert (x>=0&& x < self.row && y >=0&& y < Self.col,"Index out of range.") returnData[x][y]}Set{assert (x>=0&& x < self.row && y >=0&& y < Self.col,"Index out of range.") Data[x][y]=NewValue}} Subscript (X:int)-[Double] {Get{assert (x>=0&& x < Self.row,"Index out of range") returnData[x]}Set(vector) {assert (Vector.count= = Self.col,"Column number does not match.") Data[x]=vector} }}varMatrix = Matrix (row:2, col:2) matrix[1,1]//0matrix[1,1] =20
Matrix[1, 1] //
matrix[0]//[0, 0]matrix[1]//[0,]matrix[0] = [Ten, -]matrix[0]//[Ten,]matrix[1]//[0, 20]
matrix[0][0] //10
Matrix[0][0] = 1000
matrix[0][0] //1000
Swift-----Subscript (subscript)