Junior
Πώς θα υλοποιούσατε ένα λεξικό σε Swift χρησιμοποιώντας έναν πίνακα;
sobes.tech AI
Απάντηση από AI
Χρησιμοποιήστε μια δομή ή μια κλάση για την αναπαράσταση ζευγών "κλειδί-τιμή" και στη συνέχεια αποθηκεύστε αυτές τις δομές/κλάσεις σε έναν πίνακα.
struct KeyValuePair<Key, Value> {
let key: Key
let value: Value
}
struct ArrayBasedDictionary<Key: Equatable, Value> {
private var elements: [KeyValuePair<Key, Value>] = []
// Προσθήκη ή ενημέρωση τιμής με βάση το κλειδί
mutating func setValue(_ value: Value, forKey key: Key) {
if let index = elements.firstIndex(where: { $0.key == key }) {
// Βρέθηκε το κλειδί, ενημερώστε την τιμή
elements[index] = KeyValuePair(key: key, value: value)
} else {
// Δεν βρέθηκε το κλειδί, προσθέστε ένα νέο ζευγάρι
elements.append(KeyValuePair(key: key, value: value))
}
}
// Λήψη τιμής με βάση το κλειδί
func getValue(forKey key: Key) -> Value? {
return elements.first(where: { $0.key == key })?.value
}
// Διαγραφή με βάση το κλειδί
mutating func removeValue(forKey key: Key) {
elements.removeAll(where: { $0.key == key })
}
}
// Παράδειγμα χρήσης
var myDictionary = ArrayBasedDictionary<String, Int>()
myDictionary.setValue(10, forKey: "a")
myDictionary.setValue(20, forKey: "b")
myDictionary.setValue(30, forKey: "a") // Ενημέρωση της τιμής για το "a"
print(myDictionary.getValue(forKey: "a") ?? "nil") // Έξοδος: 30
print(myDictionary.getValue(forKey: "b") ?? "nil") // Έξοδος: 20
print(myDictionary.getValue(forKey: "c") ?? "nil") // Έξοδος: nil
myDictionary.removeValue(forKey: "a")
print(myDictionary.getValue(forKey: "a") ?? "nil") // Έξοδος: nil