Swift數組是聲明有以下幾種,
var countries:[String] = ["China","American","Russia"]
var capitals:Array<String> = ["Bejing","Washington","Moscow"]
var fruits = ["apple","orange","banana","pineapple"] //自動推斷類型
var defaultValueArray = [Int](count: 5, repeatedValue: 0) //建立一個預設值都為0長度為5的整形數組
遍例數組有以下幾種方式,第一種是像别的程式設計語言一樣通過數組下标來循環遍例變量
for i in 0..<countries.count{
println(countries[i])
}
第二種是直接遍例
for value in fruits{
println(value)
第三種是借助一個Tuple來遍例數組,Tuple中第一個為下标索引,第二個為值
for (index,value) in enumerate(fruits) {
println("index:\(index) value:\(value)")
往數組中添加元素,此時數組中就有五個水果啦
fruits.append("Lemon")
在指定的位置添加一個元素
fruits.insert("Waterlemon", atIndex: 0) 此時第一個元素就是Waterlemon啦
說完添加就得說删除了,看以下的方法不用解釋了,你懂得。
fruits.removeAtIndex(0)
fruits.removeLast()
<code>removeAll</code>方法接受一個參數,允許清空數組時是否保持數組的容量,該參數預設值為<code>false</code>,即将數組的<code>capacity</code>容量設定為0。
fruits.removeAll(keepCapacity: false)
判斷數組是否為空
fruits.isEmpty
反轉數組
fruits.reverse()