find the key associated with a value in a map in swift

To find the key associated with a certain value in a Dictionary (also known as a Map), you can iterate through its key-value pairs and check if the current value equals the target value. Here's an example implementation in Swift:

main.swift
let myMap = ["apple": 3, "banana": 5, "orange": 2]

func findKey(forValue value: Int, inMap map: [String: Int]) -> String? {
    for (key, val) in map {
        if val == value {
            return key
        }
    }
    return nil
}

let targetValue = 5
if let key = findKey(forValue: targetValue, inMap: myMap) {
    print("The key for value \(targetValue) is \(key)")
} else {
    print("Value \(targetValue) not found in the map")
}
438 chars
18 lines

In this example, myMap is a Dictionary with String as the key type and Int as the value type. The findKey(forValue:inMap:) function takes a target value and a map as input, and returns the corresponding key if found, or nil if not found.

We iterate through the key-value pairs of the map using a for-in loop, and check if the current value equals the target value using the == operator. If it does, we return the current key. If we finish iterating through all key-value pairs without finding a match, we return nil.

Finally, we call the findKey(forValue:inMap:) function with a target value of 5 and the myMap dictionary. If a key is found, we print a message with the key and the target value. Otherwise, we print a message indicating the target value was not found in the map.

related categories

gistlibby LogSnag