need help understanding how to use dictionaries

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

  1. theprizerevealed macrumors member

    Joined:
    Feb 26, 2016
    #1
    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
    
        }
    
    } 
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

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

    https://developer.apple.com/library...x.html#//apple_ref/doc/uid/TP40014097-CH3-ID0

    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 member

    Joined:
    Feb 26, 2016
    #3
    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

    Joined:
    Oct 12, 2009
    #4
    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
     

Share This Page