Swift Sets: как использовать и зачем? (С примерами)

В этом руководстве вы узнаете о наборах, создании наборов, их изменении и некоторых общих операциях с наборами.

В предыдущей статье о Swift Arrays мы узнали о создании массива, который может содержать несколько значений в упорядоченном списке.

Но если нам нужно убедиться, что список может содержать значение только один раз, мы используем набор в Swift.

Что такое набор?

Наборы - это просто контейнер, который может содержать несколько значений типа данных в неупорядоченном списке и обеспечивает уникальный элемент в контейнере (т.е. все данные появляются только один раз).

Неупорядоченный список означает, что вы не получите элементы в том же порядке, в котором вы определили элементы в наборе.

Основное преимущество использования наборов перед массивами заключается в том, что вам нужно убедиться, что элемент появляется только один раз, а порядок элементов не важен.

Значения, хранящиеся в наборе, должны быть хешируемыми . Это означает, что он должен предоставить свойство hashValue. Это важно, потому что наборы неупорядочены, и для доступа к элементам наборов используется hashValue.

Все основных типов Свифта (например String, Int, Double, и Bool) являются hashable по умолчанию, и может быть использован в качестве набора типов значений. Однако вы также можете создать свой Hashable Type в Swift, который можно сохранить в наборе.

Как объявить набор в Swift?

Вы можете создать пустой набор, указав тип как Set, а затем тип данных, которые он может хранить внутри.

Пример 1: Объявление пустого набора

 let emptyIntSet:Set = () print(emptyIntSet) 

ИЛИ

 let emptyIntSet:Set = Set() print(emptyIntSet) 

Когда вы запустите программу, вывод будет:

 ()

В приведенной выше программе мы объявили константу emptyIntSet типа, Setкоторая может хранить несколько значений целого числа и инициализирована 0 значениями.

Поскольку Swift - это язык вывода типов, вы также можете создать набор напрямую, не указывая тип данных, но должны инициализировать с некоторыми значениями, чтобы компилятор мог определить его тип как:

Пример 2: Объявление набора с некоторыми значениями

 let someIntSet:Set = (1, 2, 3, 4, 5, 6, 7, 8, 9) print(someIntSet) 

Когда вы запустите программу, вывод будет:

 (2, 4, 9, 5, 6, 7, 3, 1, 8)

В приведенной выше программе мы объявили константу someIntSet, которая может хранить наборы Integer без явного указания типа. Однако нам нужно писать :Setпри определении переменной, иначе Swift создаст для нас массив.

Кроме того, в качестве массивов мы инициализировали набор значениями 1, 2, 3, 4, 5, 6, 7, 8, 9, используя ()скобки.

Как вы узнали, когда вы пытаетесь напечатать значения внутри набора как print(someIntSet), вы получите результаты в другом порядке, чем вы определили элементы в наборе, потому что он хранит значения без определенного порядка. Поэтому каждый раз при обращении порядок меняется.

Пример 3: Объявление набора с повторяющимися значениями

 let someStrSet:Set = ("ab","bc","cd","de","ab") print(someStrSet) 

Когда вы запустите программу, вывод будет:

 («de», «ab», «cd», «bc»)

В приведенной выше программе мы определили повторяющееся значение ab в наборе. И. когда мы пытаемся получить доступ к значению внутри набора с помощью print(someStrSet), повторяющееся значение автоматически удаляется из набора. Следовательно, set гарантирует уникальные элементы / значения внутри него.

Вы также можете объявить набор со своим собственным типом Hashable в Swift. Чтобы узнать больше, посетите Swift Hashable.

Как получить доступ к элементам набора в Swift?

Вы не можете получить доступ к элементам набора, используя синтаксис индекса как массивы. Это потому, что наборы неупорядочены и не имеют индексов для доступа к элементам.

Итак, вам нужно получить доступ к набору, используя его методы и свойства или используя циклы for-in.

Пример 4: Доступ к элементам набора

 var someStrSet:Set = ("ab", "bc", "cd", "de") for val in someStrSet ( print(val) ) 

Когда вы запустите программу, вывод будет:

 de ab cd bc 

В приведенной выше программе мы получаем val в другом порядке, чем элементы набора, потому что наборы неупорядочены в отличие от массивов.

Вы также можете получить доступ к элементу набора, напрямую удалив значение из набора, как показано ниже:

Пример 5: Доступ к элементам набора с помощью remove ()

 var someStrSet:Set = ("ab", "bc", "cd", "de") let someVal = someStrSet.remove("cd") print(someVal) print(someStrSet) 

Когда вы запустите программу, вывод будет:

 Необязательно ("cd") ("de", "ab", "bc") 

В приведенной выше программе вы можете видеть, что метод remove возвращает необязательную строку. Поэтому рекомендуется выполнить дополнительную обработку, как показано ниже. Чтобы узнать больше о дополнительных возможностях, посетите Swift Optionals.

Пример 6: Дополнительная обработка для remove ()

 var someStrSet:Set = ("ab", "bc", "cd", "de") if let someVal = someStrSet.remove("cd") ( print(someVal) print(someStrSet) ) else ( print("cannot find element to remove") ) 

Когда вы запустите программу, вывод будет:

 cd ("de", "ab", "bc") 

Как добавить новый элемент в набор?

Вы можете добавить новый элемент в набор, используя insert()метод в Swift.

Пример 7: Добавить новый элемент с помощью insert ()

 var someStrSet:Set = ("ab", "bc", "cd", "de") someStrSet.insert("ef") print(someStrSet) 

Когда вы запустите программу, вывод будет:

 ("ab", "de", "cd", "ef", "bc")

In the above program, we used the set's insert() method to add a new element to a set. Since, sets are unordered, the position of the inserted element isn't known.

Set Operations

Another main advantage of using Sets is you can perform set operations such as combining two sets together, determining which values two sets have in common etc. This operations are similar to the Set operation in Mathematics.

1. Union

The union of two sets a and b is the set of elements which are in a, or b, or in both a and b.

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 2, 4, 6, 8) print(a.union(b)) 

When you run the above program, the output will be:

 (8, 2, 9, 4, 5, 7, 6, 3, 1, 0)

2. Intersection

The intersection of two sets a and b is the set that contains all elements of a that also belong to b.

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 7, 6, 8) print(a.intersection(b)) 

When you run the above program, the output will be:

 (7, 3)

Therefore, print(a.intersection(b)) outputs a new set with values (7, 3) that are common in both a and b.

3. Subtracting

The subtraction of two sets a and b is the set that contains all elements of a but removing the elements that also belong to b.

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 7, 6, 8) print(a.subtracting(b)) 

When you run the above program, the output will be:

 (5, 9, 1)

Therefore, print(a.subtracting(b)) outputs a new set with values (5, 9, 1).

4. Symmetric Difference

The symmetric difference of two sets a and b is the set that contains all elements which are in either of the sets but not in both of them.

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 7, 6, 8) print(a.symmetricDifference(b)) 

When you run the above program, the output will be:

 (5, 6, 8, 0, 1, 9)

Therefore, print(a.symmetricDifference(b)) outputs a new set with values (5, 6, 8, 0, 1, 9).

Set Membership and Equality Operations

Set Equality

You can use == operator to check whether two sets contains same elements or not. It returns true if two sets contains same elements otherwise returns false.

Example 5: Set equality operations

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 7, 6, 8) let c:Set = (9, 7, 3, 1, 5) if a == b ( print("a and b are same") ) else ( print("a and b are different") ) if a == c ( print("a and c are same") ) else ( print("a and c are different") ) 

When you run the above program, the output will be:

 a and b are different a and c are same

Set membership

You can also check relationship between two sets using the following methods:

  • isSubset(of:)This method determines whether all of the values of a set are contained in the specified set.
  • isSuperset(of:) This method determines whether a set contains all of the values in a specified set
  • isStrictSubset(of:) or isStrictSuperset(of:): This method determines whether a set is a subset or superset, but not equal to, a specified set.
  • isDisjoint(with:) This method determines whether two sets have no values in common.

Example 6: Set membership operations

 let a: Set = (1, 3, 5, 7, 9) let b: Set = (0, 3, 1, 7, 6, 8, 9, 5) print("isSubset:", a.isSubset(of: b)) print("isSuperset:", b.isSuperset(of: a)) print("isStrictSubset:", a.isStrictSubset(of: b)) print("isDisjointWith:", a.isDisjoint(with: b)) 

When you run the above program,the output will be:

 isSubset: true isSuperset: true isStrictSubset: true isDisjointWith: false 

Let's analyze methods used inside the print statement below:

  • isSubsetreturns true because the set b contains all the elements in a
  • isSupersetreturn true because b contains all of the values of a.
  • isStrictSubsetreturns true because set b contains all the element in a and both sets are not equal.
  • isDisjointWithreturns false because a and b have some values in common.

Some helpful built in Set functions & properties

1. isEmpty

This property determines if a set is empty or not. It returns true if a set does not contain any value otherwise returns false.

Example 7: How isEmpty works?

 let intSet:Set = (21, 34, 54, 12) print(intSet.isEmpty) 

When you run the program, the output will be:

 false

2. first

This property is used to access first element of a set.

Example 8: How first works?

 let intSet = (21, 34, 54, 12) print(intSet.first) 

When you run the program, the output will be:

 Optional(54)

Since set is an unordered collection, the first property does not guarantee the first element of the set. You may get other value than 54.

Similarly, you can use last property to access last element of a set.

3. insert

The insert function is used to insert/append element in the set.

Example 9: How insert works?

 var intSet:Set = (21, 34, 54, 12) intSet.insert(50) print(intSet) 

When you run the program, the output will be:

 (54, 12, 50, 21, 34)

4. reversed

This function returns the elements of a set in reverse order.

Example 10: How reversed() works?

 var intSet:Set = (21, 22, 23, 24, 25) print(intSet) let reversedSet = intSet.reversed() print(reversedSet) 

When you run the program, the output will be:

 (22, 23, 21, 24, 25) (25, 24, 21, 23, 22) 

5. count

This property returns the total number of elements in a set.

Example 11: How count works?

 let floatSet:Set = (10.2, 21.3, 32.0, 41.3) print(floatSet.count) 

When you run the program, the output will be:

 4

6. removeFirst

This function removes and returns the first value from the set.

Example 12: How removeFirst works?

 var strSet:Set = ("ab", "bc", "cd", "de") let removedVal = strSet.removeFirst() print("removed value is (removedVal)") print(strSet) 

When you run the program, the output will be:

 removed value is de ("ab", "cd", "bc") 

Точно так же вы также можете использовать removeAllфункцию для очистки набора.

Интересные статьи...