Cannot invoke 'decode' with an argument list of type '(GenericDM.Type, from: String?)'

I've been using app.quicktype.io to generate the code to decode JSON. I'm facing a problem now that I have not seen before.

I've been using app.quicktype.io to generate the code to decode JSON. I'm facing a problem now that I have not seen before.

First, I have this simple struct:

import Foundation

struct GenericDM: Codable {
let status, statusMessage: String
let result: [Result]

enum CodingKeys: String, CodingKey {
    case status
    case statusMessage = "status_message"
    case result
}

}

struct Result: Codable {
let applicationID, applicationName, applicationType, suFirstName: String
let suMiddleName, suLastName, suAge, suDob: String
let suRace: String
let suAddress: SuAddress
let createdTime, updatedTime: Int

enum CodingKeys: String, CodingKey {
    case applicationID = "application_id"
    case applicationName = "application_name"
    case applicationType = "application_type"
    case suFirstName = "su_first_name"
    case suMiddleName = "su_middle_name"
    case suLastName = "su_last_name"
    case suAge = "su_age"
    case suDob = "su_dob"
    case suRace = "su_race"
    case suAddress = "su_address"
    case createdTime = "created_time"
    case updatedTime = "updated_time"
}

}

struct SuAddress: Codable {
let addrLine1, addrLine2, stName, addrCity: String
let addrState, addrCounty, addrPin: String

enum CodingKeys: String, CodingKey {
    case addrLine1 = "addr_line_1"
    case addrLine2 = "addr_line_2"
    case stName = "st_name"
    case addrCity = "addr_city"
    case addrState = "addr_state"
    case addrCounty = "addr_county"
    case addrPin = "addr_pin"
}

}

func newJSONDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
decoder.dateDecodingStrategy = .iso8601
}
return decoder
}

func newJSONEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
encoder.dateEncodingStrategy = .iso8601
}
return encoder
}

// MARK: - URLSession response handlers

extension URLSession {
fileprivate func codableTask<T: Codable>(with url: URL, completionHandler: @escaping (T?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
return self.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
completionHandler(nil, response, error)
return
}
completionHandler(try? newJSONDecoder().decode(T.self, from: data), response, nil)
}
}

func genericDMTask(with url: URL, completionHandler: @escaping (GenericDM?, URLResponse?, Error?) -&gt; Void) -&gt; URLSessionDataTask {
    return self.codableTask(with: url, completionHandler: completionHandler)
}

}

Then, I read a JSON file and try to decode the data from a different class:

    let bundle = Bundle.main
let path = bundle.path(forResource: "MockGenericData", ofType: "json")
let jsonData = try? String.init(contentsOf: URL.init(fileURLWithPath: path!))
let genericDM = try? newGenericDMJSONDecoder().decode(GenericDM.self, from: jsonData)

I temporarily need to read from that mockup file before I can get it from the backend.

However, I'm getting Cannot invoke 'decode' with an argument list of type '(GenericDM.Type, from: String?)' and I don't understand why.

Anybody has any idea?

How to change the UITextfield text with data from JSON based on the value from UISlider in Swift 4?

Right now I have the UIText field hard coded and changing according to the value on the UISlider.

Right now I have the UIText field hard coded and changing according to the value on the UISlider.

    @IBAction func sliderValueChanged(_ sender: UISlider) {
let currentValue = Int(sender.value)

levelLabel.text = "Food Level \(currentValue)"


if currentValue == 1 {


    foodDescription.text = "Healthy Vegetables: (raw, steamed, roasted, frozen). "

I was able to connect to the REST api and get the JSON results parsed.

Now, the slider has values from 1 to 6.

The JSON is structured like this:

{
"Level1": "3",
"LevelCategory": "This includes all meats, seafood and poultry. We recommend organic sources here. Eggs (with and without yolk) are also in this section.",
"LevelID": "1275a833-b250-4de0-b29a-0b926e57bff0",
"LevelName": "Proteins"
}

What's the best way to check the slider value and get the correct Level Category, Name etc. using the JSON data?

Right now, I'm using IF for the slider value. Is there a better way to do this?

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

JSON Tutorial For Beginners | What is JSON | Learning JSON with JavaScript

Explore JSON and how JavaScript Objects can be used to access data within JSON data format and output to your web page

Guide to learning how to use JavaScript Objects and JSON data. JSON is the most popular format for data exchange between applications. If you are interested in connected to a web API chances are its JSON formatted. Learn to use AJAX to connect and bring JSON data into your JavaScript!

This course shows you how to work with JSON formatted data, output content, loop JSON data, Parse JSON and a whole lot more.

JSON (JavaScript Object Notation) is a syntax for data. JSON is easier to use than XML and human readable. Most modern web APIs output data in JSON formats. It's a lightweight data interchange format that is quickly becoming the default format for data exchange on internet today! JSON is lightweight, language independent and easy to read and write. JSON is better than XML and more popular!

Within the lessons of this course we will explore

  • JavaScript data types used to hold variables and how they work
  • JSON and how to write JSON data
  • How to add values into a JSON object
  • Accessing JSON data and bringing it into JavaScript
  • JavaScript JSON parse and stringify methods
  • Adding JSON to local storage
  • Retrieving back data within JSON formats, updating and working with JSON
  • Connecting to a web API using fetch
  • Retrieving JSON data from a web API and outputting the results into your web page
  • Iterating threw multiple results from an API
  • Google Spreadsheet data as JSON and how to practice retrieving data
  • All of the source code and resources are in included
  • Explore different methods of working with the JSON data stringify and parsing
  • How JavaScript objects can use Arrays to hold multiple items
  • How JavaScript arrays work and store data

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about JavaScript and JSON

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript Programming Tutorial | Full JavaScript Course for Beginners 2019

The complete beginner’s guide to JSON

The Complete Guide to JSON Web Tokens

JWT Fundamentals for Beginners

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

New ES2019 Features Every JavaScript Developer Should Know

How to parse JSON in background thread after Alamofire request finishes?

After getting&nbsp;JSON&nbsp;data from&nbsp;Alamofire&nbsp;request, I want to parse it on background thread, because, parsing process is difficult and has some logic in my case. The first idea to solve was executing a&nbsp;async&nbsp;operation on background thread with synchronous request with&nbsp;Alamofire. But, as I've read,&nbsp;Alamofire&nbsp;works completely asynchronously. The second solution of mine was executing a parsing&nbsp;JSON&nbsp;process in another thread after&nbsp;responseJSON&nbsp;of&nbsp;Alamofire&nbsp;gets called. After it completes, I will update my UI in main thread. Here is how it looks:

After getting JSON data from Alamofire request, I want to parse it on background thread, because, parsing process is difficult and has some logic in my case. The first idea to solve was executing a async operation on background thread with synchronous request with Alamofire. But, as I've read, Alamofire works completely asynchronously. The second solution of mine was executing a parsing JSON process in another thread after responseJSON of Alamofire gets called. After it completes, I will update my UI in main thread. Here is how it looks:

.responseJSON { (response) in //callback of Alamofire
    if response.result.isSuccess {
        let json = JSON(response.result.value!)
        DispatchQueue(label: "parsing", qos: .userInitiated).async {
            self.parseJSON(json)
            DispatchQueue.main.async {
                self.updateUI()
            }
        }
    }
}

But is it a good approach to solve this problem? I just don't want to parse a JSON on main thread, because parsing process has a couple of for loops and other operations, and, I think it cause on drawing of UI related stuff.