swift 陣列

weixin_33797791發表於2018-10-31

1.省略型別的陣列宣告

var types = ["none","warning","error"]
  1. 宣告一個空的陣列
var numbers = [String]()
print(numbers)
  1. 陣列中新增元素
numbers.append("one")
numbers += ["two"]
numbers.insert("zore", at: 0)
  1. 判斷陣列元素個數
let count = numbers.count

5.判斷陣列是否為空

if !numbers.isEmpty {
    
    print("陣列不為空")
}

6.陣列交換位置

numbers.swapAt(1, 2)
print(numbers)

7.刪除下標為2的元素

numbers.remove(at: 2)

8.刪除最後一個元素

numbers.removeLast()

9.移除所有元素

numbers.removeAll()

10.陣列合並

var array1 = ["xing","wei","xin"]
var array2 = ["shu","ju","zhong","xin"]
let array = array1 + array2
  1. 遍歷陣列
for key in array {
    
    print("--------\(key)")
}

12.通過enumerate遍歷陣列

for (index,value) in array.enumerated() {
    
    print("\(index)個元素為\(value)");
    
}

13.過濾陣列元素

var typex = ["xingwei","qunainxiat","vue"]
let newTypes = typex.filter { $0.count < 6 } //["vue"]

14.建立包含100個元素的陣列 ["條目0", "條目1" ... "條目99"]

let items = Array(0..<100).map{"條目\($0)"}

相關文章