迅捷cad
In this tutorial, we’ll be discussing the use cases of Swift Set. We’ll look at the basic syntax and some important operations performed using Swift sets.
在本教程中,我们将讨论Swift Set的用例。 我们将介绍基本语法和使用Swift集执行的一些重要操作。
1.迅捷套装 (1. Swift Set)
- Swift Sets are a data structure type that holds unique values of the same type in an unordered fashion. Swift集是一种数据结构类型,它以无序的方式保存相同类型的唯一值。
- Set can only take types that conform to the
Hashable
protocol. Set只能采用符合Hashable
协议的类型。 - Sets store the values based on the
hashValue()
thanks to the hashable protocol. Hence the access time is constant in sets.hashValue()
协议,集合基于hashValue()
存储值。 因此,访问时间在组中是恒定的。 - A hashValue is an Integer such that it is the same for all objects that compare equally. If
a == b
is true thena.hashValue == b.hashValue
must be true. hashValue是一个Integer,因此对于相等比较的所有对象都相同。 如果a == b
为true,则a.hashValue == b.hashValue
必须为true。
2. Swift Set与数组 (2. Swift Set vs Array)
- Sets store unique values. Arrays can store repeated. 设置存储唯一值。 数组可以重复存储。
- Sets are unordered. Printing a set won’t give the same order as it was defined. Arrays are ordered. 集是无序的。 打印一组的顺序与定义的顺序不同。 数组是有序的。
- Sets store values based on hash values. Arrays don’t. 根据哈希值设置存储值。 数组没有。
- Sets have a constant lookup time thanks to storing by hash values. Arrays don’t. Hence Sets are faster than Array. 由于使用散列值存储,因此集具有恒定的查找时间。 数组没有。 因此集合比数组快。
3. Swift Set vs字典 (3. Swift Set vs Dictionary)
Both are unordered, but dictionaries can have same values in two different keys. Sets have unique values always.
两者都是无序的,但是字典在两个不同的键中可以具有相同的值。 集始终具有唯一值。
Let’s launch our Swift Playground in XCode and get started.
让我们在XCode中启动我们的Swift Playground并开始使用。
4.声明一组 (4. Declaring a set)
We can declare a set in the following manner(s):
我们可以通过以下方式声明集合:
var emptySet = Set<String>()
emptySet = []
var filledSet : Set<Int> = [3,1,2]
var typeInferredSet : Set = ["Red","Yellow","Green"]
print(filledSet)
print(emptySet)
print(typeInferredSet)
To declare a set we must use the keyword Set followed by the type inside .
Swift can infer the type as well from the values set on the right-hand side.
要声明一个集合,我们必须使用关键字Set及其后的type。
Swift也可以从右侧设置的值推断类型。
The above code prints the following in the console.
![swift set initialization](https://i-blog.csdnimg.cn/blog_migrate/f4424ca27df273174fef124924593280.png)
上面的代码在控制台中输出以下内容。
5.从集合中插入和删除元素 (5. Inserting and Removing Elements from a Set)
We can insert and remove elements in a set in the following manner:
我们可以按以下方式在一组中插入和删除元素:
let typeInferredSet : Set = ["Red","Yellow","Green"]
//typeInferredSet.insert("Wednesday") //compilation error. Cannot insert in immutable Sets
var emptySet = Set<String>()
emptySet.insert("One")
emptySet.insert("Two")
emptySet.insert("One")
//emptySet.insert(3) //compilation error
var filledSet : Set<Int> = [3,1,2]
var x = filledSet.remove(2)
var y = filledSet.remove(0)
let storeIndex = filledSet.index(of: 1)
if let unwrapped = storeIndex {
filledSet.remove(at: unwrapped)
}
filledSet.removeAll() //removes all the elements
typeInferredSet.contains("Red") //returns true
print("empty set: \(emptySet) x is: \(x ?? -1) y is: \(y ?? -1)")
//Prints
//empty set: ["One", "Two"] x is: 2 y is: -1
- We cannot insert elements in Sets with
let
constant. 我们不能使用let
常量在Set中插入元素。 - The removed elements can be retrieved in a var/let variable. 可以在var / let变量中检索已删除的元素。
- The removed elements are returned as optionals. 移除的元素作为optional返回。
- If the removed element doesn’t exist, it returns a nil which is wrapped in the optional. 如果删除的元素不存在,则返回一个nil,该nil包装在可选元素中。
- Duplicate elements that are inserted get ignored. 插入的重复元素将被忽略。
- Inserting an element with a different type would give a compilation error. 插入其他类型的元素会产生编译错误。
- To remove an element using it’s index we need to pass the
Set<Type>.Index
of the element intoremove(at:)
. For this we need to retrieve the index usingindex(of:)
and pass the value by optional unwrapping usingif let
statement 要使用其索引删除元素,我们需要将元素的Set<Type>.Index
传递到remove(at:)
。 为此,我们需要使用index(of:)
检索索引index(of:)
并使用if let
语句通过可选的展开方式传递值 x ??
checks whether the Optional is is null or not, if it is, it prints the value on the right of ?? else it prints the value from the optional after unwrapping.x ??
检查Optional是否为null,如果为null,则在??的右边打印该值。 否则,解包后会从可选参数中打印值。
6.在集合中查找元素 (6. Find an element in a set)
contains()
method checks whether the given element is present in the set and returns a boolean value.
contains()
方法检查集合中是否存在给定元素,并返回布尔值。
let typeInferredSet : Set = ["Red","Yellow","Green"]
typeInferredSet.contains("Red") //returns true
7.套装容量 (7. Capacity of the set)
The count
property returns the number of elements present in the set.
isEmpty
checks whether the set is empty or not and returns a boolean.
count
属性返回集合中存在的元素数。
isEmpty
检查集合是否为空,并返回一个布尔值。
var filledSet : Set<Int> = [3,1,2]
filledSet.removeAll()
filledSet.count //returns 0
fillSet.isEmpty //returns true
typeInferredSet.count returns 3
8.从数组创建集合 (8. Creating a Set from an Array)
We can create a set from an array using the following syntax:
我们可以使用以下语法从数组创建集合:
let intSet = Set([5,1,4,6])
let myArray = ["Monday","Tuesday"]
let anotherSet = Set(myArray)
let sequenceSet = Set<Int>(1...5)
print(sequenceSet) // [5, 2, 3, 1, 4]
We can create a set from an array by passing the array inside the Set()
. We can also create a set using Ranges in Swift.
我们可以通过将数组传递给Set()
从数组中创建一个集合。 我们还可以在Swift中使用Ranges创建一个集合。
9.遍历一组 (9. Iterating over a set)
We can iterate over a set in the following manner using a for in loop.
我们可以使用for in循环以以下方式迭代集合。
var newSet : Set<String> = ["Yay","Nay","Meh"]
for words in newSet{
print(words)
}
//prints
//Nay
//Meh
//Yay
10.对集合进行排序 (10. Sorting the set)
Use the sorted()
method to keep the set in an ordered way.
使用sorted()
方法以有序方式保留集合。
var newSet : Set<Int> = [5,4,1,2,3]
print(newSet)
for words in newSet.sorted(){
print(words)
}
The above code prints 1 to 5. It sorts the set in ascending order by default.
上面的代码显示1到5。默认情况下,它按升序对集合进行排序。
11.快速设置操作 (11. Swift Set Operations)
Swift Set operations are useful for comparing two data sets. Following venn diagrams illustrate the commonly used operations.
![swift set diagram apple docs](https://cdn.journaldev.com/wp-content/uploads/2018/03/swift-sets-diagram-docs-e1521114493141.png)
快速设置操作对于比较两个数据集很有用。 以下维恩图说明了常用的操作。
- subset and superset
var setA : Set<String> = ["A","B","C","D","E"] var setB : Set<String> = ["C","D","E"] var setC : Set<String> = ["A","B","C","D","E"] setB.isSubset(of: setA) //true setB.isStrictSubset(of: setA) //true setC.isSubset(of: setA) //true setC.isStrictSubset(of: setA) //false setA.isSuperset(of: setB) //true setA.isStrictSuperset(of: setB) //true
子集和超集isStrictSubset()
returns true if the set is a subset of the passed in superset but NOT an exact copy.
isStrictSuperset()
returns true if the set is a superset of the passed in subset but NOT an exact copy.如果集合是传入的超集的子集,但不是精确副本,则
isStrictSubset()
返回true。
如果集合是传入子集的超集而不是精确副本,则isStrictSuperset()
返回true。 - disjoint and union
Two sets are disjointed if no elements are common. Union of two sets joins both of them (ignoring duplicates).
var setA : Set<String> = ["A","B","C","D","E"] var setB : Set<String> = ["C","D","E"] var setC : Set<String> = ["A","B","C","D","E"] var setD : Set<String> = ["A","F"] setD.isDisjoint(with: setB)//true setD.isDisjoint(with: setA)//false var unionSet = setD.union(setA) // {"B", "A", "F", "C", "D} var inter = setD.intersection(setA) // {"A"}
union
needs to store the result in a new variable.intersection
method would get the common elements from both the sets.
脱节与联合setA.substract(setB)
would remove the elements from A that are their in B too and return a new set. setA won’t be changed unless we reassign the new set as setA only.如果没有共同的元素,则两组不相交。 两个集合的并集将两个集合都连接在一起(忽略重复项)。
union
需要将结果存储在新变量中。intersection
方法将从这两个集合中获取公共元素。setA.substract(setB)
也会从A中删除其在B中的元素,并返回一个新集合。 除非我们将新集合仅重新分配为setA,否则不会更改setA。
That’s all for a quick roundup on Swift Set.
这就是Swift Set的快速总结。
Reference: Apple Docs
参考: Apple Docs
迅捷cad