Swift Subscripts
A subscript is a shortcut for accessing elements in a collection, sequence, or custom type, using the bracket syntax instance[index] to get and set values.
The array's array[0] and the dictionary's dict["key"] are both subscripts; you can define the same syntax in your own class, struct, or enum.
Subscript Syntax and Applications
Define a subscript with the subscript keyword; its syntax falls between an instance method and a computed property: it has a parameter list and a return type, but no name.
Example
import Foundation
struct
TimesTable
{
let multiplier
:
Int
// A read-only subscript can omit the get keyword and braces
subscript
(
index
:
Int
)
Int
{
return
multiplier
index
}
}
let threeTimesTable
=
TimesTable
(
multiplier
:
3
)
(
"6 times 3 is (threeTimesTable[6])"
)
Running result:
3 的 6 倍是 18
To support both reading and writing, write the full form of the subscript parameters, using get and set to handle reading and writing respectively.
Example
import Foundation
struct
Weekday
{
private
var days
=
[
"Sunday"
,
"Monday"
,
"Tuesday"
,
"Wednesday"
,
"Thursday"
,
"Friday"
,
"Saturday"
]
subscript
(
index
:
Int
)
String
{
get
{
return
days
[
index
]
}
set
{
days
[
index
]
=
newValue
}
}
}
var week
=
Weekday
(
)
(
week
[
1
]
)
week
[
0
]
=
"RUNOOB"
(
week
[
0
]
)
Running result:
Monday
RUNOOB
The new value in set is called newValue by default, but you can also write set(value) to give it a custom name.
A subscript can take any number of parameters with unrestricted types, so the same type can provide multiple subscript implementations distinguished by parameter types and counts; this is subscript overloading.
Example
import Foundation
struct
Matrix
{
let rows
:
Int, columns
:
Int
var grid
:
[
Double
]
init
(
rows
:
Int, columns
:
Int
)
{
self.
rows
=
rows
self.
columns
=
columns
// Use a one-dimensional array to simulate a two-dimensional matrix, with all elements initialized to 0.0
grid
=
Array
(
repeating
:
0.0
, count
:
rows
columns
)
}
// A subscript can take multiple parameters
subscript
(
row
:
Int, column
:
Int
)
Double
{
get
{
return
grid
[
(
row
columns
)
column
]
}
set
{
grid
[
(
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
(
mat
[
0
,
0
]
, mat
[
0
,
1
]
, mat
[
1
,
0
]
, mat
[
1
,
1
]
)
Running result:
1.0 2.0 3.0 5.0
Matrix uses a one-dimensional array to store data, and the subscript converts the two-dimensional coordinates (row, column) into a one-dimensional offset row * columns + column.
Read-Only Subscript Shorthand
A subscript that only provides get is a read-only subscript; in this case you can omit the get keyword and the outer braces, writing the return statement directly.
The TimesTable above uses this shorthand. By contrast, Weekday's subscript needs set, so it must write the full get/set structure.
| form | Syntax | Assignability |
|---|---|---|
| Read-Only Subscripts | subscript(i: Int) -> T { ... } |
No |
| Read-Write Subscripts | subscript(i: Int) -> T { get { ... } set { ... } } |
Is |
| Custom New Value Name | subscript(i: Int) -> T { get { ... } set(v) { ... } } |
Is |
Note:A read-only subscript cannot appear on the left side of an assignment statement. Writing to a read-only subscript
instance[0] = xproduces a compile-time error.
Type Subscript: static subscript
Similar to type methods, subscripts can also be declared as type subscripts with static, accessed directly through the type itself without creating an instance.
Example
import Foundation
enum
Planet
:
Int
{
case
mercury
=
1
, venus, earth, mars
// Type subscript: accessed through the type itself, no instance needed
static
subscript
(
n
:
Int
)
Planet
{
return
Planet
(
rawValue
:
n
)
!
}
}
let mars
=
Planet
[
4
]
(
mars
)
(
Planet
[
2
]
==
.
venus
)
Running result:
mars
true
When a type subscript in a class is declared with class, subclasses may override it; when declared with static, overriding is not allowed.
Subscripts and inout
A subscript expression is a readable and writable location, so it can be passed directly to a function as an inout parameter, and modifications made inside the function are written back to the original element.
Example
import Foundation
var numbers
=
[
1
,
2
,
3
,
4
,
5
]
// A subscript expression can be passed directly as an inout parameter
func
double
(
_ value
:
inout Int
)
{
value
=
2
}
double
(
&
numbers
[
2
]
)
(
numbers
)
// swapAt also reads and writes elements via subscripts internally
numbers.
swapAt
(
0
,
4
)
(
numbers
)
Running result:
[1, 2, 6, 4, 5]
[5, 2, 6, 4, 1]
If a subscript has only get and no set, passing it as an inout parameter produces a compile-time error, because the function cannot write changes back.
Common questions
Subscripts are simple to use, but the following pitfalls are worth noting.
Subscript Out-of-Bounds Crashes Immediately
Array subscripts offer no remedy beyond bounds checking; accessing an out-of-range index triggers a runtime error. When defining a custom subscript, it is advisable to check whether the index is valid first.
Dictionary Subscripts Return an Optional
The result of a dictionary subscript lookup is an optional type; it returns nil when the key does not exist, so it cannot be used directly as a plain value and must be unwrapped.
Subscripts Cannot Have Default Parameters
A subscript can have multiple parameters, but default values are not supported; overloads must be distinguished by parameter types and count.