Hi there,
I am very new to programming. I am going through all the chapters and solving all the challenges.
I got stuck with Q6 in Dictionaries. I referred to the solution and couldn’t clearly understand the solution. Very specifically I am unable to interpret the for loop with an if statement where it says
" if isValuePresent[value] != nil {
return false // duplicate value detected
}"
Could you please help me breakdown the solution. Following are the details:
Question: Write a function that returns true if all of the values of a dictionary [String:Int]
are unique. Use a dictionary to test uniqueness. This is the function signature:
func isInvertible(_ dictionary: [String: Int]) → Bool
Solution:
func isInvertible(_ dictionary: [String: Int]) → Bool {
var isValuePresent: [Int: Bool] = [:]
for value in dictionary.values {
if isValuePresent[value] != nil {
return false // duplicate value detected
}
isValuePresent[value] = true
}
return true
}
Thank you.
isValuePresent is being used as a “temporary notepad” to keep track of which values have already been encountered during the function.
At the start of each loop you check if the value from the original dictionary is in the isValuePresent dictionary. If it isn’t, you go ahead and add it to your “temporary” dictionary. If it is present, you return false (since the goal of the function is to inform you whether all values in a given dictionary are unique).
As you continue to loop, your isValuePresent dictionary continues to grow. If you ever come across a duplicate value, you return false. If your function exits the loop, it is an indication that there are no dupes and are able to return true.
Hope this helps
1 Like
Thank you for your prompt response.
It makes a lot of sense now after reading your reply. I need to develop this level of thinking. And I know it will only come through lot of practice.
Thanks again for your help.
Best Regards
Minesh
The return false
statement, instruction and line of code inside the if
statement acts like a break
statement for the for
loop: it exits early from the loop if you have actually found any duplicate values inside the original and initial dictionary since there is no point of going through all of the other dictionary’s remaining elements, items and values in this case (if at least two values are equal, then the dictionary doesn’t contain only and just unique items in the first place and to begin with after all for sure and for good indeed).