📜  Swift数组Array

📅  最后修改于: 2020-10-09 15:40:06             🧑  作者: Mango

## 如何在Swift中声明数组？

### 示例1：声明一个空数组

``````let emptyIntArr:[Int] = []
print(emptyIntArr)
``````

``[ ]``

``````let emptyIntArr:Array = Array()
print(emptyIntArr)
``````

### 示例2：声明具有某些值的数组

``````let someIntArr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(someIntArr)
``````

``[1, 2, 3, 4, 5, 6, 7, 8, 9]``

### 示例3：声明一个包含指定数量的单个重复值的数组

``````let arrWithRepeatingValues = Array(repeating: "Hello, World", count: 4)
print(arrWithRepeatingValues)
``````

``["Hello, World", "Hello, World", "Hello, World", "Hello, World"]``

## 值如何存储在数组中？

``let intArr = [21, 34, 54, 12]``

## 如何在Swift中访问数组元素？

### 示例4：访问数组的元素

``````let intArr = [21, 34, 54, 12]
print(intArr[0])
print(intArr[1])
print(intArr[2])
print(intArr[3])
``````

``````21
34
54
12
``````

## 如何在Swift中修改/添加数组元素？

### 示例5：修改数组的元素

``````var intArr = [21, 34, 54, 12]
intArr[0] = 12
intArr[1] = 42
intArr[2] = 45
intArr[3] = 21
print(intArr)
``````

``[12, 42, 45, 21]``

### 示例6：整体修改数组

``````var intArr = [21, 34, 54, 12]
intArr = [1,2,3]
print(intArr)
``````

``[1, 2, 3]``

### 示例7：使用下标语法在数组中添加新元素(无效)

``````var intArr = [21, 34, 54, 12]
intArr[4] = 10
``````

``fatal error: Index out of range``

## 内置的一些有用的数组函数和属性

### 1. isEmpty

###### 示例8：isEmpty如何工作？
``````let intArr = [21, 34, 54, 12]
print(intArr.isEmpty)
``````

``false``

### 2.首先

###### 示例9：首先如何工作？
``````let intArr = [21, 34, 54, 12]
print(intArr.first)
``````

``Optional(21)``

### 3.追加

append 函数用于在数组末尾插入/附加元素。

###### 示例10：append如何工作？
``````var intArr = [21, 34, 54, 12]
intArr.append(32)
print(intArr)
``````

``[21, 34, 54, 12, 32]``

``````var firstArr = [1,2,3,4]
var secondArr = [5,6,7,8]
firstArr.append(contentsOf: secondArr)
print(firstArr)
``````

``[1, 2, 3, 4, 5, 6, 7, 8]``

### 4.插入

###### 示例11：插入如何工作？
``````var intArr = [21,34,54,12]
intArr.insert(22, at: 1)
print(intArr)
``````

``[21, 22, 34, 54, 12]``

### 5.删除

###### 示例12：删除如何工作？
``````var strArr = ["ab","bc","cd","de"]
let removedVal = strArr.remove(at: 1)
print("removed value is \(removedVal)")
print(strArr)
``````

``````removed value is bc
["ab", "cd", "de"]
``````

### 6.反转

###### 示例13：reversed()如何工作？
``````var intArr = [21,22,23,24]
let reversedArr = Array(intArr.reversed())
print(reversedArr)
``````

``[24, 23, 22, 21]``

### 7.计数

###### 示例14：计数
``````let floatArr = [10.2,21.3,32.0,41.3]
print(floatArr.count)
``````

``4``

## 要记住的事情

``````let intArr = [21, 34, 54, 12]
print(intArr[-1])
``````

``fatal error: Index out of range``

``````var intArr = [21, 34, 54, 12]
if let index = intArr.index(of: 34) {
print("found index")
let val =  intArr.remove(at: index)
print(val)
}
``````

``````found index
34
``````