Sets क्या हैं
एक set unique items का एक group है जिसमें कोई duplicates और कोई particular order नहीं, एक bag जैसा जहां आप हर तरह के marble का सिर्फ एक रख सकते हैं।
In this page:
Syntax
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
// 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))
Login to try C/C++/Java/PHP code in the editor
Set Operations
Sets दो sets को combine या compare करने के लिए .union(), .intersection(), और .subtracting() जैसे mathematical operations support करते हैं।
उदाहरण: Set Operations
// 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())
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- यह मान लेना कि एक set insertion order को array की तरह संरक्षित रखता है; sets explicitly unordered हैं।
- एक duplicate value जोड़ना set के बढ़ने की उम्मीद से; duplicates अपने आप ignore किए जाते हैं।
- किसी ऐसे type के लिए set उपयोग करना जो
Hashableनहीं है; किसीSetमें हर element type कोHashableconform करना चाहिए।
चैप्टर सारांश
- एक
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: