Monday, June 30, 2014

Arrays

Arrays

//Type inference 
var fruitList = ["apple", "banana"]

//Explicit format: 
var fruitList: Array<String> = ["apple", "banana"]
//Explicit shortcut format: 
var fruitList: [String] = ["apple", "banana"]

fruitList[1] = "orange"
//fruitList =["apple", "orange"]

Number of Items

println("The fruitList contains \(fruitList.count) items.")
//Console output: The fruitList contains 2 items.


Item Addition

fruitList[2] = "strawberry"
//Wrong: fatal error: Array index out of range

//Correct Method1: Use "append" to add item:
fruitList.append("strawberry")
//fruitList = ["apple", "orange", "strawberry"]

//Correct Method2: Use "+=":
fruitList += ("kiwifruit")
//fruitList = ["apple", "orange", "strawberry", "kiwifruit"]


//Insert an Item to a specific location
fruitList.insert("mango", atIndex: 2)
//fruitList = ["apple", "orange", "mango", "strawberry", "kiwifruit"]


Item Removal

fruitList.removeAtIndex(3)
//fruitList = ["apple", "orange", "mango", "kiwifruit"]

var removedItem = fruitList.removeLast()
//fruitList = ["apple", "orange", "mango"]
//removedItem = "kiwifruit"

Check if the array is empty:

if fruitList.isEmpty {

}

for loop: Iterating over the array

for itemCount in fruitList {
    println(itemCount)
}

//Console output:
apple
orange
mango

================================

Initialize an empty array
var intArray = [Int]()
//intArray is of type Int[]

println("intArray has \(intArray.count) items.")

//Console output: intArray has 0 items.


Add new item
intArray.append(2)
//intArray = [2]


Reset the array

intArray = []

Other method for creating arrays
var oneArray = Int[](count: 2, repeatedValue: 1)  //[1, 1]
var zeroArray = Int[](count: 3, repeatedValue: 0) //[0, 0, 0]
var combinedArray = oneArray + zeroArray          //[1, 1, 0, 0, 0]

No comments:

Post a Comment