2
2
.
.
4
4
.
.
6
6
A
A
r
r
r
r
a
a
y
y
s
s
I
I
n
n
f
f
o
o
Array is a list of Elements. 2D Array is also just a list of elements where every Element is another Array.
You can access Elements using square brackets or normal Methods.
S
S
y
y
n
n
t
t
a
a
x
x
Array Data Type is declared by placing Element's Data Type inside square brackets like [String].
Empty Array is declared using square brackets [].
Array with initial values is declared using Array Literal (list of comma separated values inside square brackets [1, 2]).
A
A
r
r
r
r
a
a
y
y
o
o
f
f
S
S
t
t
r
r
i
i
n
n
g
g
s
s
[
[
R
R
]
]
Below is an example of using basic Array functionalities on Array of Strings.
Example
// DECLARE ARRAY
var elements : [String] = [] //Declare empty Array
var people : [String] = ["ZERO", "FIRST"] //Declare Array. Initilize it with elements.
var people = ["ZERO", "FIRST"] //Declare Array. Data Type os implied by Array Literal.
// ADD/REMOVE ELEMENTS
people.append("SECOND") //Append element at the end of Array
people.append("THIRD") //Append
people.insert("NEW" , at:2) //Insert element at index 2. Others are shifted.
people.insert("SUB ZERO" , at:0) //Insert element at the begining of Array
people.remove(at:2) //Remove element at index 2. Others are shifted.
// GET/REPLACE ELEMENTS
let element = people[2] //Read element at index 2
people[2] = "NEW PERSON" //Replace element at index 2
// PRINT ARRAY
print(element)
print(people) //["SUB ZERO", "ZERO", "FIRST", "NEW", "THIRD"]
dump (people) //Print Array
// ITERATE THROGUH ARRAY
for person in people { print(person) }
for person in people.reversed() { print(person) }
for (index, person) in people.enumerated() { print("\(index) - \(person)") }
A
A
r
r
r
r
a
a
y
y
o
o
f
f
s
s
t
t
r
r
u
u
c
c
t
t
s
s
Below is an example of using basic Array functionalities on Array of Structs.
Example
// DECLARE STRUCT
struct Person {
let id : Int
let name : String
let age : Int
}
// DECLARE ARRAY
var elements : [String] = [] //Declare empty Array
var people : [Person] = [ //Declare Array
Person( id:0, name:"ZERO" , age:0 ), //Initilize it with elements.
Person( id:1, name:"FIRST", age:10 )
]
// ADD/REMOVE ELEMENTS
people.append(Person( id:0, name:"SECOND" , age:20)) //Append element at the end of Array
people.append(Person( id:0, name:"THIRD" , age:30)) //Append
people.insert(Person( id:0, name:"NEW" , age:20), at:2) //Insert element at index 2. Others are shifted.
people.insert(Person( id:0, name:"SUB ZERO", age:20), at:0) //Insert element at the begining of Array
people.remove(at:2) //Remove element at index 2. Others are shifted.
// GET/REPLACE ELEMENTS
let element = people[2] //Read element at index 2
people[2] = Person( id:0, name:"NEW PERSON", age:20) //Replace element at index 2
// PRINT ARRAY
print(element)
print(people)
dump(people)
// ITERATE THROGUH ARRAY
for person in people { print(person) }
for person in people.reversed() { print(person) }
for (index, person) in people.enumerated() { print("\(index) - \(person)") }