Sobes.tech
Junior

In what cases would you use a dictionary in your code?

sobes.tech AI

Answer from AI

  • For storing key-value pairs where keys are unique.
  • When quick data lookup by key is required.
  • To represent JSON objects (Swift: [String: Any]).
  • When creating temporary storage for settings or data.
  • To group data by a certain criterion (key).
// Example of using a dictionary to store user settings
let userSettings: [String: Any] = [
    "theme": "dark",
    "fontSize": 16,
    "notificationsEnabled": true
]

// Accessing a value by key
if let theme = userSettings["theme"] as? String {
    print("Theme: \(theme)")
}