迅捷cad
In this tutorial, we’ll be discussing about Swift Array. If you don’t know how Optional in Swift work, you can refer here before proceeding forward.
在本教程中,我们将讨论Swift数组。 如果您不知道Swift中的Optional如何工作,可以在继续进行之前参考这里 。
迅捷数组 (Swift Array)
Array in Swift is used to store an ordered collection of values of any type (we can have more than one types in an array).
Swift中的数组用于存储任何类型的值的有序集合(数组中可以有多个类型)。
Arrays that are defined as a var
are mutable whereas the ones defined with let
are immutable. An example of each is given below:
定义为var
数组是可变的,而用let
定义的数组是不可变的 。 下面是每个示例的示例:
var arrayOfStrings:[String] = ["Hello", "Playground"]
let constantArray :[String] = ["Hello", "Playground"] //Can't modify this
Let’s dive into our playground to have a deeper look at Arrays.
让我们深入游乐场,更深入地了解Arrays。
Swift数组示例 (Swift Arrays Example)
Let’s look at different operations with swift array.
让我们看一下swift数组的不同操作。
在Swift中创建数组 (Creating Array in Swift)
You can either declare the type or Swift infers it as shown below.
您可以声明类型,也可以通过Swift进行推断,如下所示。
//String array with type explicitly declared.
var arrayOfStrings:[String] = ["Hello", "Playground"]
//String array with type inferred.
var arrayOfStrings = ["Hello", "Playground"]
快速数组长度 (Swift Array Length)
To get the array’s length we’ll invoke the function count
on the instance of array using the dot operator as shown below.
为了获得数组的长度,我们将使用点运算符在数组实例上调用函数count
,如下所示。
print(arrayOfStrings.count) //prints 2
向数组添加元素 (Adding elements to an array)
We can add elements to the end of an array the function append
is called on the instance of array as shown below.
我们可以将元素添加到数组的末尾,在数组实例上调用函数append
,如下所示。
arrayOfStrings.append("New Member")
arrayOfStrings.append(1)// Compilation error
print(arrayOfStrings.count) //prints 3
let mutableArray = ["I can't", "be", "modified"]
mutableArray.append("1") //Compile-time error.
Since the array is of the type String
, we’ll get an error while adding an Int
.
append
function would give a compile time error when used on an immutable array.
由于数组的类型为String
,因此添加Int
时会出错。
在不可变数组上使用append
函数会产生编译时错误。
一次附加多个元素 (Append multiple elements at once)
arrayOfStrings += ["Append", "Multiple", "Elements"]
arrayOfStrings += [1,2] //Compilation error. Can't add elements of a different type
创建一个空数组 (Creating an empty array)
To create an empty array of a particular type use the following syntax:
要创建特定类型的空数组,请使用以下语法:
var someArray:[Int] = []
//or
var someArray = [Int]()
//Example 1
var intArray = [Int]()
intArray.append(3)
intArray.count //prints 1
intArray = [] //clears the contents. Back to being empty.
创建具有默认值的数组 (Creating an array with default values)
Following syntax is used to create an array with repeating values and count.
以下语法用于创建具有重复值和计数的数组。
var intArray: [Int] = Array(repeating: 10, count: 5)
print(intArray) //prints [10, 10, 10, 10, 10]
var boolArray: [Bool] = Array(repeating: false, count: 5) // [false, false, false, false, false]
Array()
is the default function that contains two arguments repeating
where we set the default value for each element and count
is for setting the number of elements.
Array()
是默认函数,包含两个repeating
参数,我们在其中设置每个元素的默认值,而count
是用于设置元素的数量。
访问和修改数组 (Accessing and Modifying an Array)
Accessing and modifying array elements using subscripts is more or less similar to other languages.
使用下标访问和修改数组元素或多或少类似于其他语言。
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray[0] = 2
customIntArray[customIntArray.count-1] = 11
访问和修改一系列元素 (Accessing and modifying a range of elements)
To access a range of elements in an array we use the subscript syntax as shown below
要访问数组中的一系列元素,我们使用下标语法,如下所示
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray[0...5] // returns [1, 4, 5, 7, 10, 2]
Note: The range of elements returned are inclusive of the start and end indexes ( 0 and 5 in the above case).
注意 :返回的元素范围包括开始和结束索引(在上述情况下为0和5)。
We can modify the values of the range of elements in place too as shown below
我们也可以如下所示修改元素范围的值
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray[0...5] = [0,0,0,0,0]
print(customIntArray) //prints [0, 0, 0, 0, 0, 4, 5, 34, 33, 11, 13, 17]
It’s possible to modify the range of values with a set of values having different length as shown below:
可以使用具有不同长度的一组值来修改值的范围,如下所示:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray[0...5] = [0]
print(customIntArray) //prints [0, 4, 5, 34, 33, 11, 13, 17]
In the above code we’ve replaced a range of 5 elements with a single element.
在上面的代码中,我们用单个元素替换了5个元素。
在指定索引处插入和删除 (Inserting and removing at specified index)
To insert an element at a specified index we use the following syntax:
要在指定索引处插入元素,我们使用以下语法:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray.insert(0, at: 0)
print(customIntArray) //prints [0, 1, 4, 5, 7, 10, 2, 4, 5, 34, 33, 11, 13, 17]
The insert
function inserts the value at the mentioned index and shifts the array elements to the right of it by an offset of 1.
insert
函数将值插入提到的索引处,并将数组元素向右移偏移量1。
To remove an element at a specified index we use the following syntax:
要删除指定索引处的元素,我们使用以下语法:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
customIntArray.remove(at: 0) //returns 1
print(customIntArray)//prints [4, 5, 7, 10, 2, 4, 5, 34, 33, 11, 13, 17]
Note: The remove function returns the removed element too. You can store it if you need to as below
注意:remove函数也返回被删除的元素。 如果需要,可以将其存储如下
var removedElement = customIntArray.remove(at: 0)
To remove all elements from an array we need to invoke the method removeAll()
on the array.
To check if an array is empty or not we invoke the method isEmpty()
on the instance of array as shown below:
要从数组中删除所有元素,我们需要在数组上调用方法removeAll()
。
要检查数组是否为空,我们在数组实例上调用方法isEmpty()
,如下所示:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
if customIntArray.isEmpty {
print("array is empty")
}
else{
print("false") //this gets printed
}
访问数组的第一个和最后一个元素 (Accessing the first and last elements of an array)
Swift provides us with first
and last
properties to access the first and last elements of an array.
The returned value is an optional
type as shown below:
Swift为我们提供了first
和last
属性,以访问数组的first和last元素。
返回值是optional
类型,如下所示:
var customIntArray = [1,4,5,7,10,2,4,5,34,33,11,13,17]
var first = customIntArray.first
print(first) //prints Optional(1)
var last = customIntArray.last
print(last) //prints Optional(17)
if let l = last{
print(l) //prints 17
}
else{print("couldn't retrieve the last element") }
We’ve used if let
to safely get the last element’s value
To retrieve and remove the last element of an array, we call the function popLast()
which pops the last element from the array and returns it’s optional value.
我们使用过if let
可以安全地获取最后一个元素的值
要检索和删除数组的最后一个元素,我们调用函数popLast()
,该函数从数组中弹出最后一个元素并返回其可选值。
if let l = customIntArray.popLast(){
print(l) //prints 17
}
else{print("couldn't retrieve the last element") }
Note: In the above example if the array is empty, the else statement would’ve been printed.
注意 :在上面的示例中,如果数组为空,则将打印else语句。
在Swift数组中查找元素 (Find an element in Swift array)
To check if an element is present inside an array we invoke the function contains()
on the instance of the array as shown below:
要检查数组中是否存在元素,我们在数组实例上调用函数contains()
,如下所示:
var oddArray = [1,3,5,7]
print(oddArray.contains(2)) //false
print(oddArray.contains(5)) //true
Note: The contains()
function returns as soon as the first match is found.
contains()
function has another implementation that expects a condition in the form of a function/closure as the parameter. An example is mentioned below.
注意 :一旦找到第一个匹配项, contains()
函数就会返回。
contains()
函数具有另一个实现,该实现期望以函数/闭包形式的条件作为参数。 下面提到一个例子。
var oddArray = [1,3,5,7]
print(oddArray.contains(where: {$0 > 5})) //prints true
print(oddArray.contains(where: {$0 > 10})) //prints false
//check if the array contains any even number
print(oddArray.contains(where: {$0%2 == 0})) //prints false
We’ve used a closure as the where clause in the above code snippets. If you’re unaware of closures refer here.
在上面的代码片段中,我们已使用闭包作为where子句。 如果您不知道闭包,请参考这里 。
快速反转数组 (Reverse an array in swift)
To reverse an array we call the function reverse()
on the instance of array as shown below:
为了反转数组,我们在数组的实例上调用函数reverse()
,如下所示:
var oddArray = [1,3,5,7]
oddArray.reverse()
print(oddArray) //prints [7, 5, 3, 1]
遍历数组 (Looping over an array)
A for-in
loop allows us to loop over an array without the use of indexes as shown below:
for-in
循环使我们可以循环使用数组,而无需使用索引,如下所示:
var oddArray = [1,3,5,7]
for element in oddArray {
print(element)
}
To display index value as well as element we call the enumerated()
function on the array in the for-in
loop as shown below:
为了显示索引值和元素,我们在for-in
循环中在数组上调用enumerated()
函数,如下所示:
var stringArray = ["Hey", "How", "You","Doing"]
for (index, value) in stringArray.enumerated() {
print("\(index) : \(value)") //prints index value pair
}
//prints :
0 : Hey
1 : How
2 : You
3 : Doing
To iterate over the array in reverse order inside the for-in
loop we call the function reversed()
over the array.
为了在for-in
循环内以相反的顺序遍历数组,我们在数组上调用了reversed()
函数。
var oddArray = [1,3,5,7]
for number in oddArray.reversed() {
print(number)
}
//prints:
7
5
3
1
合并和比较两个数组 (Combining and comparing two arrays)
To combine two arrays you can simply add them as shown below:
要合并两个数组,您可以简单地将它们添加如下所示:
let oddArray = [1,3,5,7]
let evenArray = [0,2,4,6,8]
let completeArray = evenArray + oddArray // contains [0, 2, 4, 6, 8, 1, 3, 5, 7]
To compare if two arrays are equal or not we use the function elementsEqual()
as shown below:
为了比较两个数组是否相等,我们使用elementsEqual()
,如下所示:
let oddArray = [1,3,5,7]
let oddArrayTwo = [1,3,5,7]
let evenArray = [0,2,4,6,8]
evenArray.elementsEqual(oddArray) //false
oddArray.elementsEqual(oddArrayTwo) //true
快速多维数组 (Swift Multidimensional Array)
A multidimensional array is declared in the following manner.
多维数组以以下方式声明。
var arrayOfArrays = [[String]]()
var aA = ["AA","AB","AC"]
var bA = ["BA","BB","BC"]
var cA = ["CA","CB","CC"]
arrayOfArrays.append(aA)
arrayOfArrays.append(bA)
arrayOfArrays.append(cA)
print(arrayOfArrays)//prints: [["AA", "AB", "AC"], ["BA", "BB", "BC"], ["CA", "CB", "CC"]]
arrayOfArrays[0].append("AD")
arrayOfArrays[1].append("BD")
arrayOfArrays[2].append("CD")
print(arrayOfArrays)//prints: [["AA", "AB", "AC", "AD"], ["BA", "BB", "BC", "BD"], ["CA", "CB", "CC", "CD"]]
This brings an end to swift array tutorial.
这样就结束了快速数组教程。
迅捷cad