Dictionaries क्या हैं
var name = [key1: value1, key2: value2]
name[key] // returns Value? (optional)
name[key] = value // add or update
name[key] = nil // remove
name.removeValue(forKey: key)
Creating and Accessing a Dictionary
एक dictionary literal square brackets में key: value pairs list करता है, और values key से subscript syntax उपयोग करके देखी जाती हैं, जो एक optional return करता है।
उदाहरण: Creating and Accessing a Dictionary
// Declare a constant `capitals`, set to `["France": "Paris", "Japan": "Tokyo"]`
let capitals = ["France": "Paris", "Japan": "Tokyo"]
// Print `capitals["France"] as Any` to the console
print(capitals["France"] as Any)
// Print `capitals["Germany"] as Any` to the console
print(capitals["Germany"] as Any)
Login to try C/C++/Java/PHP code in the editor
Adding and Updating Entries
किसी dictionary के subscript को assign करना एक नया key-value pair जोड़ता है या एक मौजूदा को update करता है।
उदाहरण: Adding and Updating Entries
// Declare a mutable variable `inventory`, initialized to `["apples": 10, "bananas": 5]`
var inventory = ["apples": 10, "bananas": 5]
inventory["oranges"] = 8
inventory["apples"] = 12
// Print `inventory["apples"]!` to the console
print(inventory["apples"]!)
// Print `inventory["oranges"]!` to the console
print(inventory["oranges"]!)
Login to try C/C++/Java/PHP code in the editor
Removing Entries
एक key-value pair को या तो इसकी value nil सेट करके या removeValue(forKey:) call करके हटाया जा सकता है।
उदाहरण: Removing Entries
// Declare a mutable variable `scores`, initialized to `["Alice": 90, "Bob": 75]`
var scores = ["Alice": 90, "Bob": 75]
scores["Bob"] = nil
// Print `scores` to the console
print(scores)
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि subscript access जैसे
dict["key"]हमेशा सीधे value return करता है; यह असल में एक optional return करता है क्योंकि key मौजूद नहीं हो सकती। - यह भूल जाना कि Swift में dictionaries की कोई guaranteed order नहीं है -- दो बार iterate करना अलग orders दे सकता है।
- एक dictionary literal बनाते समय उसी key को दो बार उपयोग करके अनजाने में एक key की value overwrite करना।
- एक dictionary keys को values से map करता है,
[KeyType: ValueType]लिखा गया। - किसी dictionary को subscript करना (
dict[key]) हमेशा एक optional return करता है, क्योंकि key गायब हो सकती है। .updateValue(),removeValue(forKey:), और direct subscript assignment किसी dictionary को modify करते हैं।- Dictionaries unordered हैं -- iterate करते समय insertion order पर भरोसा न करें।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: