Rao Rao - 1 year ago 47
Swift Question

Pick value stored against a hash key which ends with a specific character

I have a hash of type

[String: [String: AnyObject]]()
something like below,

"asndfkjsndkjnf_1": {"A": "2"},
"jckxjbcvkjbsdsdfkz_2": {"G": 3},
"sahgkshbgskdssjf_3": {"T": '1'},
"asdhlsfldsnfsldk_4": {"C": 4}

I want to pick the value of hash entry whose key ends with
, since hashes don't have indexes I am finding it a bit difficult to retrieve item I want without knowing the complete key.

Answer Source

The normal way of fetching a value from a dictionary by using optional binding:

let dict: [String:AnyObject] = [
    "asndfkjsndkjnf_1": ["A": "2"],
    "jckxjbcvkjbsdsdfkz_2": ["G": 3],
    "sahgkshbgskdssjf_3": ["T": "1"],
    "asdhlsfldsnfsldk_4": ["C": 4]

if let innerDict = dict["asndfkjsndkjnf_1"] as? [String:AnyObject] {
    if let valueA = innerDict["A"] as? String {

But in a comment you say

I don't know the complete key to retrieve the value, I only know that the hash's key ends with a certain pattern

You can use .hasSuffix() to find which key ends with a certain string, then use this key to fetch the inner value.

Let's say you want to find the value for the key ending with "_3":

for key in dict.keys where key.hasSuffix("_3") {
    if let innerDict = dict[key] as? [String:AnyObject] {
        if let innerValue = innerDict["T"] as? String {