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.swift438 chars18 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.
gistlibby LogSnag