sorted() और contains()
In this page:
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
let numbers = [5, 2, 8, 1, 9]
print(numbers.sorted())
Login to try C/C++/Java/PHP code in the editor
Custom Sorting with sorted(by:)
.sorted(by:) को एक closure pass करना आपको बिल्कुल define करने देता है कि दो elements को कैसे compare करना चाहिए, जैसे descending order में sort करना।
उदाहरण: Custom Sorting with sorted(by:)
// 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)
Login to try C/C++/Java/PHP code in the editor
Checking Membership with contains
.contains() जांचता है कि कोई specific value किसी collection में मौजूद है या नहीं, और .contains(where:) किसी custom condition को satisfy करने वाले किसी element के लिए जांचता है।
उदाहरण: Checking Membership with contains
// 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 }))
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि
.sorted()जगह पर sort करता है; यह हमेशा एक नया array return करता है, original को unchanged छोड़ते हुए। - किसी बड़े array पर loop में बार-बार
.contains()उपयोग करना जब एकSetतेज़ membership checks देता। - यह भूल जाना कि
.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 करता है या नहीं, एकBoolreturn करते हुए।.contains(where:)exact equality के बजाय एक custom condition से match करने वाली element के लिए जांचता है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: