Swift Sets: Bagaimana Cara Menggunakannya dan Mengapa? (Dengan Contoh)

Dalam tutorial ini, Anda akan belajar tentang set, membuat set, memodifikasinya dan beberapa operasi umum dalam set.

Di artikel Swift Arrays sebelumnya, kita belajar tentang membuat array yang bisa menampung banyak nilai dalam daftar berurutan.

Tetapi, jika kita harus memastikan sebuah daftar hanya dapat menampung nilai sekali, kita menggunakan satu set di Swift.

Apakah satu set itu?

Set hanyalah sebuah wadah yang dapat menampung beberapa nilai tipe data dalam daftar tak berurutan dan memastikan elemen unik dalam wadah (yaitu setiap data muncul hanya sekali).

Daftar tidak berurutan berarti Anda tidak akan mendapatkan elemen dalam urutan yang sama seperti Anda mendefinisikan item dalam Set.

Keuntungan utama menggunakan Sets over array adalah ketika Anda perlu memastikan bahwa item hanya muncul sekali dan ketika urutan item tidak penting.

Nilai yang disimpan dalam satu set harus dapat di- hash . Ini berarti ia harus menyediakan properti hashValue. Ini penting karena set tidak berurutan dan menggunakan hashValue digunakan untuk mengakses elemen set.

Semua tipe dasar Swift (seperti String, Int, Double, dan Bool) adalah hashable secara default, dan dapat digunakan sebagai set jenis nilai. Namun, Anda juga dapat membuat Jenis Hashable Anda di Swift yang dapat disimpan dalam satu set.

Bagaimana cara mendeklarasikan satu set di Swift?

Anda dapat membuat set kosong dengan menentukan tipe sebagai Set diikuti dengan tipe Data yang dapat disimpan di dalamnya.

Contoh 1: Menyatakan himpunan kosong

 let emptyIntSet:Set = () print(emptyIntSet) 

ATAU

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

Saat Anda menjalankan program, hasilnya adalah:

 ()

Dalam program di atas, kami telah mendeklarasikan tipe kosongIntSet konstan Setyang dapat menyimpan beberapa nilai integer dan diinisialisasi dengan 0 nilai.

Karena, Swift adalah bahasa inferensi tipe, Anda juga dapat membuat set secara langsung tanpa menentukan Tipe Data tetapi harus menginisialisasi dengan beberapa nilai sehingga compiler dapat menyimpulkan tipenya sebagai:

Contoh 2: Mendeklarasikan himpunan dengan beberapa nilai

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

Saat Anda menjalankan program, hasilnya adalah:

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

Dalam program di atas, kami telah mendeklarasikan someIntSet konstan yang dapat menyimpan set Integer tanpa menentukan jenisnya secara eksplisit. Namun, kita perlu menulis :Setsaat mendefinisikan variabel, jika tidak Swift akan membuat array untuk kita.

Juga, sebagai array, kami telah menginisialisasi set dengan nilai 1, 2, 3, 4, 5, 6, 7, 8, 9 menggunakan ()tanda kurung.

Seperti yang telah Anda pelajari, saat Anda mencoba mencetak nilai di dalam himpunan sebagai print(someIntSet), Anda akan mendapatkan hasil dalam urutan yang berbeda dari yang Anda tentukan item dalam set karena menyimpan nilai tanpa urutan yang ditentukan. Oleh karena itu, setiap kali Anda mengakses pesanan berubah.

Contoh 3: Mendeklarasikan set dengan nilai duplikat

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

Saat Anda menjalankan program, hasilnya adalah:

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

Dalam program di atas, kami telah mendefinisikan nilai duplikat ab dalam himpunan. Dan. ketika kita mencoba mengakses nilai di dalam himpunan menggunakan print(someStrSet), nilai duplikat secara otomatis dihapus dari himpunan. Oleh karena itu, set menjamin elemen / nilai unik di dalamnya.

Anda juga dapat mendeklarasikan satu set dengan tipe Hashable kustom Anda sendiri di Swift. Untuk mempelajari lebih lanjut, kunjungi Swift Hashable.

Bagaimana cara mengakses elemen set di Swift?

Anda tidak dapat mengakses elemen set menggunakan sintaks subskrip sebagai array. Ini karena set tidak berurutan dan tidak memiliki indeks untuk mengakses elemen.

Jadi, Anda perlu mengakses set menggunakan metode dan propertinya atau menggunakan loop for-in.

Contoh 4: Mengakses elemen set

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

Saat Anda menjalankan program, hasilnya adalah:

 de ab cd bc 

Dalam program di atas, kita mendapatkan val dalam urutan yang berbeda dari elemen sebuah himpunan karena himpunan tidak berurutan tidak seperti array.

Anda juga dapat mengakses elemen dari suatu set secara langsung menghapus nilai dari set seperti di bawah ini:

Contoh 5: Mengakses elemen set menggunakan remove ()

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

Saat Anda menjalankan program, hasilnya adalah:

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

Dalam program di atas, Anda dapat melihat metode hapus mengembalikan string opsional. Oleh karena itu, sebaiknya Anda melakukan penanganan opsional seperti di bawah ini. Untuk mempelajari lebih lanjut tentang opsional, kunjungi Swift Opsional.

Contoh 6: Penanganan opsional untuk pelepasan ()

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

Saat Anda menjalankan program, hasilnya adalah:

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

Bagaimana cara menambahkan elemen baru dalam satu set?

Anda bisa menambahkan elemen baru ke set menggunakan insert()metode di Swift.

Contoh 7: Tambahkan elemen baru menggunakan insert ()

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

Saat Anda menjalankan program, hasilnya adalah:

 ("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") 

Demikian pula, Anda juga dapat menggunakan removeAllfungsi untuk mengosongkan satu set.

Artikel yang menarik...