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

sorted() और contains()

sorted() एक list को order में रखता है, और contains() बताता है कि आप जो ढूंढ रहे हैं वह असल में वहां है या नहीं।
Syntax
swift
let ascending = array.sorted()
let custom = array.sorted(by: { a, b in a > b })

array.contains(value)
array.contains(where: { condition using $0 })

Default Ascending Sort

Comparable elements के एक array पर .sorted() call करना ascending order में arranged एक नया array return करता है।

उदाहरण: Default Ascending Sort

markup
let numbers = [5, 2, 8, 1, 9]
print(numbers.sorted())

Custom Sorting with sorted(by:)

.sorted(by:) को एक closure pass करना आपको बिल्कुल define करने देता है कि दो elements को कैसे compare करना चाहिए, जैसे descending order में sort करना।

उदाहरण: Custom Sorting with sorted(by:)

markup
// Declare a constant `numbers`, set to `[5, 2, 8, 1, 9]`
let numbers = [5, 2, 8, 1, 9]
// Declare a constant `descending`, set to `numbers.sorted(by: >)`
let descending = numbers.sorted(by: >)
// Print `descending` to the console
print(descending)

Checking Membership with contains

.contains() जांचता है कि कोई specific value किसी collection में मौजूद है या नहीं, और .contains(where:) किसी custom condition को satisfy करने वाले किसी element के लिए जांचता है।

उदाहरण: Checking Membership with contains

markup
// Declare a constant `names`, set to `["Ann", "Bob", "Cara"]`
let names = ["Ann", "Bob", "Cara"]
// Print `names.contains("Bob")` to the console
print(names.contains("Bob"))
// Print `names.contains(where: { $0.count > 3 })` to the console
print(names.contains(where: { $0.count > 3 }))
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. यह मान लेना कि .sorted() जगह पर sort करता है; यह हमेशा एक नया array return करता है, original को unchanged छोड़ते हुए।
  2. किसी बड़े array पर loop में बार-बार .contains() उपयोग करना जब एक Set तेज़ membership checks देता।
  3. यह भूल जाना कि .sorted(by:) आपको descending order या custom criteria के लिए एक custom comparison closure supply करने देता है।
चैप्टर सारांश
  • .sorted() comparable elements के लिए default रूप से ascending order में एक नया array return करता है।
  • .sorted(by:) custom ordering define करने के लिए एक closure accept करता है, जैसे descending या किसी specific property के अनुसार।
  • .contains() जांचता है कि कोई collection एक दी गई element include करता है या नहीं, एक Bool return करते हुए।
  • .contains(where:) exact equality के बजाय एक custom condition से match करने वाली element के लिए जांचता है।
🔒

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.