OC和Swift數組的比較swift
下面是swift數組的具體示範數組
空數組app
let arr = [] let arr2 = [Int]() let arr3 = Array<Int>()
有值數組code
let arr4 = [1,2,3,4] let arr5:[Int] = [1,2,3,4,5] let arr6:Array<Int> = [1,2,3,4]
let建立的是不可變數組,var創鍵的是可變數組對象
var arr7:[Int] = [] arr7.append(2) print(arr7)
若是定義數組類型,全部元素必定是該類型ci
let arr8:[String] = ["aaa","bbb"]
若是沒有定義數組類型,全部元素的類型是[NSObject]rem
let arr9 = ["zhang san",19,190]
數組元素個數it
print(arr9.count) //Any 能夠存任何的對象,func //AnyObject 能夠存任何class類型的對象 let arr10:[Any] = ["zhangsan",10,190] print(arr10)
取值,某個元素ast
print(arr10[2])
取值區間class
print(arr10[0..<2])
range取值
print(arr10[Range(start: 0, end: 2)]) var arr11:[Any] = ["zhangsan",10,190]
添加元素
arr11.append("male")
加數組
arr11 += ["xiaoyu"]
插入元素
arr11.insert(81, atIndex: 2)
更新元素
arr11[4] = "remale"
刪除元素
arr11.removeFirst() arr11.removeLast() print(arr11) arr11.removeFirst(2) arr11.removeRange(Range(start: 0, end: 2)) arr11.removeRange(1...2)
刪除全部,包括刪除容量
arr11.removeAll()
刪除全部,但不刪除容量
arr11.removeAll(keepCapacity: true) print("Capacity:\(arr11.capacity)")
數組的批量操做
var arr12 = [1,2,3,4] //0,1替換成另外一個數組[80,81,82,83] arr12[0...1] = [80,81,82,83] print(arr12)
遍歷操做
for obj in arr12 { print(obj) } for obj in arr12[1...2] { print(obj) }