Junior
What can be the key and value for a dictionary?
sobes.tech AI
Answer from AI
In iOS (Swift), a dictionary (Dictionary) is a collection of key-value pairs.
-
Key can be any type that conforms to the
Hashableprotocol. This means the key must be hashable for quick lookup. For example,String,Int,UUID, and other standard types. -
Value can be any type, including structures, classes, primitives, or even other collections.
Example:
var dict: [String: Int] = ["apple": 3, "banana": 5]
// Key — String (hashable), value — Int
// You can also use custom types if they conform to Hashable:
struct User: Hashable {
let id: Int
let name: String
}
var userScores: [User: Double] = [:]
It is important that keys are immutable and hashable so that the dictionary can function correctly.