Junior — Middle
Millised andmetüübid või objektid võivad toimida võtmetena sõnaraamatutes või hajutustabelites?
sobes.tech AI
Vastus AI-lt
In dictionaries or hash tables, keys can be objects that meet the following requirements:
- Have correctly implemented equality comparison methods (
equalsin Java,isEqualin Swift) and hash code calculation (hashCodein Java). - Are immutable or at least do not change after being used as a key, to avoid search problems.
In iOS (Swift), keys in dictionaries (Dictionary) are usually types that conform to the Hashable protocol. These can be:
- Standard types:
String,Int,Double,Bool. - User-defined structures or classes that implement the
Hashableprotocol.
Example:
struct Person: Hashable {
let id: Int
let name: String
}
var dict: [Person: String] = [:]
dict[Person(id: 1, name: "Alice")] = "Developer"
Therefore, keys must be hashable and immutable for the dictionary to work correctly.