Home > Back-end >  Get special values from [AnyHashable] to other [AnyHashable]
Get special values from [AnyHashable] to other [AnyHashable]

Time:05-24

I have data which type [AnyHashable] given in below;

"options": [
                  {
                      "index": 0,
                      "label": "Choice 1"
                  },
                  {
                      "index": 1,
                      "label": "Choice 2"
                  },
                  {
                      "index": 2,
                      "label": "Choice 3"
                  }
      ],

I want to get all "label" values an the other [AnyHashable] . I cant find the best way. How can I do it?

CodePudding user response:

You can define related models and decode JSON to your model like this:


let jsonString = """
{
    "options": [
        {
            "index": 0,
            "label": "Choice 1"
        },
        {
            "index": 1,
            "label": "Choice 2"
        },
        {
            "index": 2,
            "label": "Choice 3"
        }
    ]
}
"""

struct Option: Codable {
    let index: Int
    let label: String
}

struct Model: Codable {
    let options: [Option]
}

let data = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
let model = try! decoder.decode(Model.self, from: data)
let labels = model.options.map(\.label)

print(labels)
//["Choice 1", "Choice 2", "Choice 3"]

CodePudding user response:

Thanks for your useful recommendation. I think it is some weirds but works.

  func options(for question: [String : Any?]) -> [AnyHashable] {
    
       var qoptions: [String] = []
       for val in question["options"] as! [[String:Any]] {
           let value = val["label"] as! String
           qoptions.append(value)
       }
       return qoptions as! [AnyHashable]
   }
  • Related