Swift – Arrays

 

Arrays in swift are used to store values of same data type. The syntax for arrays in swift is as shown below.

var (or let for constant) myFirstArray = [values]

Some example arrays are shown below.

var myFirstArray = []
println("myFirstArray:\(myFirstArray)")
var mySecondArray = ["Value1","Value2"]
println("mySecondArray:\(mySecondArray)")
var myThirdArray:Array = ["Value1","Value2"]
println("myThirdArray:\(myThirdArray)")
var myOptionalFourthArray:Array?
println("myOptionalFourthArray:\(myOptionalFourthArray)")

When you run the above program, we will get the following output.

myFirstArray:(
)
mySecondArray:[Value1, Value2]
myThirdArray:[Value1, Value2]
myOptionalFourthArray:nil

Adding Values to an array

In array, adding values is made easy with the use of += operator overloading. You also have append method and insert methods for inserting to array. An example is shown below

var myArray:Array = []
myArray += ["New Value 1"]
myArray += ["New Value 2"]
println("myArray:\(myArray)")

When you run the above program, we will get the following output.

myArray:[New Value 1, New Value 2, New Value 4, New Value 3]

 

Leave a Reply