📜  Swift – 集合和数组的区别

📅  最后修改于: 2022-05-13 01:54:35.700000             🧑  作者: Mango

Swift – 集合和数组的区别

数组是具有连续内存的线性数据结构。在单个变量中,我们可以存储 n 个元素。例如,如果我们想从用户那里获取 10 个输入,我们就不能初始化 10 个变量。为此,我们可以使用数组。它可以将 n 个元素存储到单个变量中。可以使用索引访问元素。

句法:

例子:

Swift
// Swift program to illustrate array
  
// Creating and initializing array
var arr:[Int] = [ 1, 2, 3, 4, 5 ]
  
// Display the array 
print(arr)


Swift
// Swift program to illustrate set
  
// Creating and initializing set
var set1:Set = [ 1, 2, 2, 2, 3, 4 ]
  
// Display the result
print(set1)


输出:

[1, 2, 3, 4, 5]

Set是一种不存在重复元素的数据结构。一般来说,在数组中,我们可以存储重复的元素,但是我们不能在集合中存储重复的元素。默认情况下,它会消除重复元素。就像在数学中一样,我们可以执行集合运算,例如并集、交集、集差等。

句法:

例子:

迅速

// Swift program to illustrate set
  
// Creating and initializing set
var set1:Set = [ 1, 2, 2, 2, 3, 4 ]
  
// Display the result
print(set1)

输出 :

[2, 4, 1, 3]

注意:这里我们在创建集合时采用了重复的元素,但是在输出中,我们可以看到没有重复。由于该集合不允许重复。每次打印集合时,元素的顺序可能会发生变化。

数组和集合的区别

Array

Set

Array is faster than set in terms of initialization.Set is slower than an array in terms of initialization because it uses a hash process.
Parentheses ( ) are used to create arrays in swiftSquare braces [ ] are used to create set in swift
The array allows to store duplicate elements in it.Set doesn’t allow to store duplicate elements in it. 
Elements in the array are arranged in order. Or we can say that arrays are ordered.Elements in the set are not arranged in any specified order Or we can say that sets are unordered.
Performance is not the main concern.Performance plays an important.