2
2
.
.
5
5
.
.
3
3
S
S
u
u
b
b
s
s
c
c
r
r
i
i
p
p
t
t
s
s
I
I
n
n
f
f
o
o
You can think of Subscript as a Method of a struct or class that is referenced using square brackets john["name"].
For each subscript you need to define
Data Type that is used for the index (Input Parameter)
Data Type that is returned (Return Value)
In below example we use subscript as alternative way of accessing fields: john["name"], john["position"].
Test.swift
//DECLARE CLASS.
class Employee {
//DECLARE STORED PROPERTIES.
var name = "unknown"
var position = "unknown";
//DECLARE SUBSCRIPT.
subscript (index: String) -> (String) {
get {
switch (index) {
case "name" : return name
case "position" : return position
default : return "unknown index";
}
}
set (newValue) {
switch (index) {
case "name" : name = newValue
case "position" : position = newValue
default : print("unknown index");
}
}
}
}
//CREATE OBJECT.
var john = Employee()
//USE SUBSCRIPTS TO STORE DATA INTO FIELDS.
john["name" ] = "Bob"
john["position"] = "Manager"
//USE SUBSCRIPTS TO RETRIEVE DATA FROM FIELDS.
print(john["name" ])
print(john["position"])