title: Am I converting JSON data to a Swift variable the long way?
body: <p>I am reading json data from a file and trying to move it into a NSDictionary and I am wondering if there is a more concise way to do it. The code shown below works fine. In my program the Astruct-type variable  has more than 25 Bstruct-type variables. I have several files similar to the one I show. So it leads to a lot of cumbersome programming.</p>
  
  <pre><code>import UIKit
  
  struct Bstruct {
      var label = String()
      var inputTypeStr = String()
      var list = [String]()
  }
  struct Astruct {
      // in real situation this has a over 25 variables
      // limited to 3 for this question
      var number = Bstruct()
      var customer = Bstruct()
      var location = Bstruct()
  }
  
  func loadJson(forFilename fileName: String) -&gt; NSDictionary? {
  
      if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
          if let data = NSData(contentsOf: url) {
              do {
                  let dictionary = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as? NSDictionary
  
                  return dictionary
              } catch {
                  print("Error!! Unable to parse  \(fileName).json")
              }
          }
          print("Error!! Unable to load  \(fileName).json")
      }
  
      return nil
  }
  
  func fillAstruct (value: NSDictionary) -&gt; Bstruct {
      return Bstruct(label: value["label"] as! String, inputTypeStr: value["inputTypeStr"] as! String, list: value["list"] as! [String])
  
  }
  var aVar = Astruct()
  let json = loadJson(forFilename: "document")! as NSDictionary
  let d = json["aTemplate"]! as! NSDictionary
  print("d = \(d)")
  
  // load d into aVar, appears to be complex particularly if the variable has a large number of variables in aVar and the json file
  
  for d1 in d {
      let key = String(describing: d1.0)
      let value = d1.1 as! NSDictionary
      switch key {
      case "number":
          aVar.number = fillAstruct(value: value)
      case "customer":
          aVar.customer = fillAstruct(value: value)
      case "location":
          aVar.location = fillAstruct(value: value)
      default: break
      }
  }
  
  print("\(aVar)")
  </code></pre>
  
  <p>The JSON file is shown below:</p>
  
  <pre><code>    {
    "aTemplate": {
      "number": {
        "label": "Number",
        "inputTypeStr": "selection",
        "list": [
          "A",
          "B",
          "C"
        ]
      },
      "customer": {
        "label": "Customer",
        "inputTypeStr": "label",
        "list": [
          ""
        ]
      },
      "location": {
        "label": "location",
        "inputTypeStr": "label",
        "list": [
          ""
        ]
      }
    }
  }
  </code></pre>