Array, Dictionary
Array
var intArray = [1,2,3] var strArray = ["A","B","C"] // With type var intArray : [Int] = [1,2,3] var strArray : [String] = ["A","B","C"] // initialize var initArray = Array(count: 3, repeatedValue: 0) // blankc var emptyArray = [] var emptyStrArray : [String] = [] emptyStrArray.append("SNSD") var emptyStrArray2 = [String]()
Methods
.count
var intArray = [1,2,3,4,5] var cnt = intArray.count
range
var intArray = [1,2,3,4,5] var val = intArray[1...2] // get 2,3
Enumeration
var intArray = [1,2,3,4,5] for val in intArray { println("Element \(val)") } for (index, val) in enumerate(intArray) { println("Element \(index) = \(val)") }
Operation
.appned(), +=, insert(), removeAtIndex()
var strArray = ["A", "B", "C"] strArray.append("D") var addArray = ["E", "F"] strArray += addArray strArray.insert("G", atIndex: 2) strArray.removeAtIndex(4)
Clear all removeAll
.removeAll()
sort
.sort
var ascArray = [1,3,5,6] ascArray.sort() var descArray = [2,3,5,5,3] descArray.sort({$0 > $1})
Dictionary
var dict = ["key1":"value1", "key2":"value2"] var emptyDict = Dictionary<String, Int>() var cnt = dict.count // If value is not exist, return nil if let tmp = dict["key3"] { println("found") } else { println("not found") }
Example2
var score : [String:Int] = [String:Int]() score["math"] = 100 score["english"] = 20
Enumeration
var dict = ["a":1, "b":2, "c":3] for (key,val) in dict { println("dict \(key) = \(val)") }
Operation
[], removeValudForKey
var dict = ["a":"A", "b":"B", "c":"C"] dict["d"] = "D" dict.removeValueForKey("b")