Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

theprizerevealed

macrumors regular
Original poster
Feb 26, 2016
183
12
I am trying to learn to use dictionaries in Swift 3; which I believe are similar to hashes in C++. I have a dictionary with several key:value pairs in it.
I want to take a certain, single key (which I won't know in advance) and extract from that dictionary the corresponding value.
I know there will be a single key with that name, although the same value will be associated with keys of different names.
After extracting that value from the key:value pair of that dictionary then I want to store that single value in a variable as a string.

What type of code could do that?

I found some code that seems it might be helpful but I'm not sure and I'm not sure too how to use that code(how to write it actually) to make it perform as I wish.

Code:
extension Dictionary where Value: Equatable {

   func someKeyFor(value: Value) -> Key? {

        guard let index = indexOf({ $0.1 == value }) else {
            return nil
        }

        return self[index].0

    }

}
 
thank you, I have determined that the problem was not with the code that I wrote, it was related to some other code. Also, I see now that the code I proposed in my first post would not be applicable. thanks for your willingness to reply
 
I sounds like you just want to take a String value from the dictionary? Are the Dictionary values the type of "Any", or is the type known?

If I understand you correctly, it would be something like this.

This takes the value from the key you provide and stores it in the dictionaryValue var.
Code:
let dictionaryValue  = dictionary["<key>"]

If the type is unknown you will need to cast the type.

Code:
let dictionaryValue  = dictionary["<key>"] as! String
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.