← Back to Swift Course | Chapter 6: Collections | Lesson 3 of 7

Sets क्या हैं

एक set unique items का एक group है जिसमें कोई duplicates और कोई particular order नहीं, एक bag जैसा जहां आप हर तरह के marble का सिर्फ एक रख सकते हैं।
Syntax
swift
var name: Set<Type> = [value1, value2]
name.insert(value)
name.contains(value)
setA.union(setB)
setA.intersection(setB)
setA.subtracting(setB)

Creating a Set

एक Set या तो explicit type annotation के साथ एक array literal से बनाया जाता है, या Set([...]) से, और अपने आप duplicate values हटाता है।

उदाहरण: Creating a Set

markup
// Declare a constant `uniqueNumbers` (a `Set`), set to `[1, 2, 2, 3, 3, 3]`
let uniqueNumbers: Set = [1, 2, 2, 3, 3, 3]
// Print `uniqueNumbers.count` to the console
print(uniqueNumbers.count)
// Print `uniqueNumbers.contains(2)` to the console
print(uniqueNumbers.contains(2))

Set Operations

Sets दो sets को combine या compare करने के लिए .union(), .intersection(), और .subtracting() जैसे mathematical operations support करते हैं।

उदाहरण: Set Operations

markup
// Declare a constant `evens` (a `Set`), set to `[2, 4, 6, 8]`
let evens: Set = [2, 4, 6, 8]
// Declare a constant `smallNumbers` (a `Set`), set to `[1, 2, 3, 4]`
let smallNumbers: Set = [1, 2, 3, 4]
// Print `evens.intersection(smallNumbers).sorted()` to the console
print(evens.intersection(smallNumbers).sorted())
// Print `evens.union(smallNumbers).sorted()` to the console
print(evens.union(smallNumbers).sorted())
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह मान लेना कि एक set insertion order को array की तरह संरक्षित रखता है; sets explicitly unordered हैं।
  2. एक duplicate value जोड़ना set के बढ़ने की उम्मीद से; duplicates अपने आप ignore किए जाते हैं।
  3. किसी ऐसे type के लिए set उपयोग करना जो Hashable नहीं है; किसी Set में हर element type को Hashable conform करना चाहिए।
चैप्टर सारांश
  • एक Set किसी defined order के बिना एक जैसे type की unique values store करता है, Set<Type> लिखा गया।
  • एक duplicate value जोड़ने का कोई effect नहीं क्योंकि sets अपने आप uniqueness enforce करते हैं।
  • Sets .contains() से तेज़ membership testing support करते हैं।
  • Union, intersection, और subtraction जैसे Set operations sets को mathematically combine करते हैं।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.