सामान्य Collection Operations
In this page:
collection.count
collection.isEmpty
let copy = array.sorted() // new sorted array
array.sort() // sorts in place
array.first // Type? (optional)
array.last
array.reversed()
count and isEmpty
ये दो properties arrays, sets, और dictionaries में एक जैसे काम करती हैं, आपको बिना loop लिखे किसी collection का size जांचने देते हुए।
उदाहरण: count and isEmpty
// Declare a constant `numbers`, set to `[5, 3, 8, 1]`
let numbers = [5, 3, 8, 1]
// Print "Count: \(numbers.count)" to the console
print("Count: \(numbers.count)")
// Print "Is empty: \(numbers.isEmpty)" to the console
print("Is empty: \(numbers.isEmpty)")
Login to try C/C++/Java/PHP code in the editor
sorted() vs sort()
.sorted() एक बिल्कुल नया sorted array return करता है original को untouched छोड़ते हुए, जबकि .sort() array को जगह पर sort करता है और इसे एक var होने की ज़रूरत है।
उदाहरण: sorted() vs sort()
// Declare a constant `original`, set to `[5, 2, 8, 1]`
let original = [5, 2, 8, 1]
// Declare a constant `sortedCopy`, set to `original.sorted()`
let sortedCopy = original.sorted()
// Print "Original: \(original)" to the console
print("Original: \(original)")
// Print "Sorted copy: \(sortedCopy)" to the console
print("Sorted copy: \(sortedCopy)")
Login to try C/C++/Java/PHP code in the editor
first, last, and reversed
.first और .last empty collections पर crash होने के बजाय सुरक्षित रूप से optionals return करते हैं, और .reversed() elements को उल्टे order में प्रदान करता है।
उदाहरण: first, last, and reversed
// Declare a constant `letters`, set to `["a", "b", "c"]`
let letters = ["a", "b", "c"]
// Print `letters.first as Any` to the console
print(letters.first as Any)
// Print `letters.last as Any` to the console
print(letters.last as Any)
// Print `Array(letters.reversed())` to the console
print(Array(letters.reversed()))
Login to try C/C++/Java/PHP code in the editor
- built-in
.isEmptyproperty उपयोग करने के बजाय किसी collection के empty होने की जांच के लिए एक manual loop लिखना। - यह भूल जाना कि
.countसभी collection types (arrays, sets, dictionaries, strings) पर uniformly काम करता है। .sort()से एक array sort करना जब आपका मतलब.sorted()था -- एक जगह पर mutate करता है, दूसरा एक नया array return करता है।
.countऔर.isEmptyarrays, sets, और dictionaries में consistently काम करते हैं।.sorted()original modify किए बिना एक नया sorted array return करता है;.sort()जगह पर sort करता है।.firstऔर.lastएक empty collection पर crash होने के बजाय सुरक्षित रूप से optionals return करते हैं।.reversed()elements को एक lazy sequence के रूप में उल्टे order में return करता है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: