Arrays क्या हैं
var name = [value1, value2, value3]
name[0]
name.append(value)
name.remove(at: index)
name.count
name.isEmpty
name.contains(value)
Creating and Accessing Arrays
एक array comma-separated values रखने वाले square brackets से बनाया जाता है, और इसके elements zero-based integer index से access किए जाते हैं।
उदाहरण: Creating and Accessing Arrays
// Declare a mutable variable `fruits`, initialized to `["apple", "banana", "cherry"]`
var fruits = ["apple", "banana", "cherry"]
// Print `fruits[0]` to the console
print(fruits[0])
// Print `fruits[2]` to the console
print(fruits[2])
// Print "Total fruits: \(fruits.count)" to the console
print("Total fruits: \(fruits.count)")
Login to try C/C++/Java/PHP code in the editor
Modifying an Array
Elements को .append() से जोड़ा जा सकता है, .remove(at:) से हटाया जा सकता है, और सीधे एक index को assign करके update किया जा सकता है।
उदाहरण: Modifying an Array
// Declare a mutable variable `numbers`, initialized to `[1, 2, 3]`
var numbers = [1, 2, 3]
// Append `4` to `numbers`
numbers.append(4)
numbers.remove(at: 0)
numbers[0] = 99
// Print `numbers` to the console
print(numbers)
Login to try C/C++/Java/PHP code in the editor
Checking Array Contents
.isEmpty और .count जैसी properties, .contains() जैसे methods के साथ, manual loops के बिना एक array inspect करने में मदद करती हैं।
उदाहरण: Checking Array Contents
// Declare a constant `scores`, set to `[80, 95, 70]`
let scores = [80, 95, 70]
// Print "Is empty: \(scores.isEmpty)" to the console
print("Is empty: \(scores.isEmpty)")
// Print "Count: \(scores.count)" to the console
print("Count: \(scores.count)")
// Print "Contains 95: \(scores.contains(95))" to the console
print("Contains 95: \(scores.contains(95))")
Login to try C/C++/Java/PHP code in the editor
- bounds से बाहर एक index access करने की कोशिश करना, जैसे एक 3-element array पर
array[10], जो nil return करने के बजाय runtime पर crash करता है। - यह भूल जाना कि
letसे declared arrays immutable हैं -- आप एक constant array से elements append या remove नहीं कर सकते। .count(elements की संख्या) को आखिरी valid index के साथ confuse करना, जो.count - 1है।
- एक array एक जैसे type की values का एक ordered, indexable collection है,
[Type]लिखा गया। varसे declared arrays को modify किया जा सकता है;letसे declared वाली नहीं।- आम operations में
.append(),.remove(at:),.count, और[]से indexing शामिल है। - एक out-of-bounds index access करना program को runtime पर crash करता है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: