need help understanding how to use dictionaries

Discussion in 'iOS Programming' started by theprizerevealed, Oct 25, 2016.

  1. theprizerevealed macrumors regular

    Feb 26, 2016
    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.

    extension Dictionary where Value: Equatable {
       func someKeyFor(value: Value) -> Key? {
            guard let index = indexOf({ $0.1 == value }) else {
                return nil
            return self[index].0
  2. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    I recommend that you look at Apple's docs on Swift for a better understanding of Dictionaries. This is the starting point

    Go to Language Guide > Collection Types and read the section on Dictionaries. There is a lot of short example code in this Language Guide and the answer to your question is in there.

    The code you show won't help.
  3. theprizerevealed thread starter macrumors regular

    Feb 26, 2016
    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
  4. Dookieman macrumors 6502

    Oct 12, 2009
    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.
    let dictionaryValue  = dictionary["<key>"]
    If the type is unknown you will need to cast the type.

    let dictionaryValue  = dictionary["<key>"] as! String

Share This Page

3 October 25, 2016