is 100 divided by 2.
Subscripts can be defined in classes, structures, and enumerations. They can be regarded as a shortcut for accessing objects, collections, or sequences, without needing to call specific assignment and access methods of the instance.
For example, using a subscript to access an element in an array instance can be written as someArray[index], and accessing an element in a dictionary instance can be written as someDictionary[key].
Multiple subscripts can be defined for the same target, and overloading is performed based on different index value types. The number of index values can also be multiple.
Subscript Syntax and Applications
Syntax
Subscripts allow you to access and assign values to an instance by passing one or more index values in square brackets after the instance.
The syntax is similar to a combination of instance methods and computed properties.
Similar to defining instance methods, defining a subscript uses the subscript keyword, and explicitly declares input parameters (one or more) and a return type.
Unlike instance methods, subscripts can be set to read-write or read-only. This approach is somewhat like the getter and setter of computed properties:
subscript(index: Int) -> Int {
get {
// 用于下标脚本值的声明
}
set(newValue) {
// 执行赋值操作
}
}
Example 1
import Cocoa
struct subexample {
let decrementer: Int
subscript(index: Int) -> Int {
return decrementer / index
}
}
let division = subexample(decrementer: 100)
print("100 除以 9 等于 \(division[9])")
print("100 除以 2 等于 \(division[2])")
print("100 除以 3 等于 \(division[3])")
print("100 除以 5 等于 \(division[5])")
print("100 除以 7 等于 \(division[7])")
The output of the above program execution is:
100 除以 9 等于 11 100 除以 2 等于 50 100 除以 3 等于 33 100 除以 5 等于 20 100 除以 7 等于 14
In the above example, an instance of a division operation is created through the subexample structure. The value 100 is passed as the constructor parameter of the structure to initialize the instance member decrementer.
You can get the result through the subscript, for example, division
Example 2
import Cocoa
class daysofaweek {
private var days = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "saturday"]
subscript(index: Int) -> String {
get {
return days[index] // 声明下标脚本的值
}
set(newValue) {
self.days[index] = newValue // 执行赋值操作
}
}
}
var p = daysofaweek()
print(p[0])
print(p[1])
print(p[2])
print(p[3])
The output of the above program execution is:
Sunday Monday Tuesday Wednesday
Usage
Depending on the usage scenario, subscripts also have different meanings.
Usually, subscripts are a shortcut for accessing elements in collections, lists, or sequences.
You can freely implement subscripts in your own specific classes or structures to provide appropriate functionality.
For example, Swift's Dictionary implements access to the values stored in its instances through subscripts. Use a value of the same type as the dictionary index in the subscript, and assign a value of the dictionary value type to this subscript to set a value for the dictionary:
import Cocoa var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] numberOfLegs["bird"] = 2 print(numberOfLegs)
The output of the above program execution is:
["ant": 6, "bird": 2, "cat": 4, "spider": 8]
The above example defines a variable named numberOfLegs and initializes a dictionary instance containing three key-value pairs with a dictionary literal. The value type stored in the numberOfLegs dictionary is inferred as Dictionary
Subscript Options
Subscripts allow any number of input index parameters, and there is no restriction on each input parameter type.
The return value of a subscript can also be of any type.
Subscripts can use variable parameters and variadic parameters.
A class or structure can provide multiple subscript implementations according to its own needs. When defining subscripts, they are distinguished by the type of the passed-in parameters. When using a subscript, the appropriate subscript implementation will automatically be matched for execution. This isSubscript Overloading。
import Cocoa
struct Matrix {
let rows: Int, columns: Int
var print: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
print = Array(repeating: 0.0, count: rows * columns)
}
subscript(row: Int, column: Int) -> Double {
get {
return print[(row * columns) + column]
}
set {
print[(row * columns) + column] = newValue
}
}
}
// 创建了一个新的 3 行 3 列的Matrix实例
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
// 通过下标脚本获取值
print("\(mat[0,0])")
print("\(mat[0,1])")
print("\(mat[1,0])")
print("\(mat[1,1])")
The output of the above program execution is:
1.0 2.0 3.0 5.0
The Matrix structure provides an initializer with two parameters, rows and columns, creating a Double-type array large enough to hold rows * columns elements. For storage, the array is sized to hold rows * columns elements, and each element is initialized to 0.0.
You can construct a new Matrix instance by passing the appropriate number of rows and columns.
Other Extensions