本教程通过实例展示了在Swift中向数组添加元素的多种方法。
数组是一组具有相同类型的元素。每个元素的访问都有一个索引。第一个元素以index=0开始,最后一个元素以index=length-1结束。
元素可以被添加到数组的开始、中间或末端。
如何在swift中向数组中添加一个元素
我们有多种方法可以添加一个元素,无论是开始、结束,还是index=0。
使用append方法将一个元素添加到数组的末端。
语法:
mutating func append(_ newElement: Element)
// add an element to end of an array
numbers.append("five")
将一个元素或子数组添加到一个数组的末端:
// add an subarray to end of an array
numbers.append(contentsOf: ["six", "seven"])
下面是一个完整的例子
import Foundation
var numbers = ["one", "two", "three", "four"]
print(numbers)
// add an element to end of an array
numbers.append("five")
print(numbers)
// add an subarray to end of an array
numbers.append(contentsOf: ["six", "seven"])
print(numbers)
insert方法在索引位置0处添加一个元素。
语法:
mutating func insert(
_ newElement: Element,
at i: Int
)
将一个元素添加到数组的索引中:
// add an element to an array index=1
numbers.insert("five",1)
将一个元素或子数组添加到一个数组的末端:
// add an subarray to array index=3
numbers.insert(contentsOf: ["six", "seven"],at:3)
下面是一个完整的例子
import Foundation
var numbers = ["one", "two", "three", "four"]
print(numbers)
// add an element to end of an array
numbers.insert("five",at:1)
print(numbers)
// add an subarray to end of an array
numbers.insert(contentsOf: ["six", "seven"],at:3)
print(numbers)
输出
["one", "two", "three", "four"]
["one", "five", "two", "three", "four"]
["one", "five", "two", "six", "seven", "three", "four"]
另一种使用+= 操作符的方法。
它将单个或多个元素添加到数组的末端。
这里有一个例子
import Foundation
var numbers = ["one", "two", "three", "four"]
print(numbers)
// add an element to end of an array
numbers += ["five"]
print(numbers)
// add an subarray to end of an array
numbers += ["six", "seven"]
print(numbers)
输出
["one", "two", "three", "four"]
["one", "two", "three", "four", "five"]
["one", "two", "three", "four", "five", "six", "seven"]