Skip to content

Instantly share code, notes, and snippets.

@alicanbatur
Last active October 2, 2017 18:24
Show Gist options
  • Save alicanbatur/bdd8c0c14a60fa595797f02dbf340cac to your computer and use it in GitHub Desktop.
Save alicanbatur/bdd8c0c14a60fa595797f02dbf340cac to your computer and use it in GitHub Desktop.
// Example JSON
var JSON = "{\n" +
"\"name\": \"Ali\",\n" +
"\"surname\": \"Batur\",\n" +
"\"age\":29\n" +
"}"
// Convert json string to data. JSON string is the response from restfull call.
var data: Data = JSON.data(using: .utf8)!
// Convert data to Dictionary
let personDictionary = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
// If you will not map this person dictionary, you will use it like this;
nameLabel.text = personDictionary["name"] ?? "" // defaut value
// What if I want you to combine name and surname, I mean put some little business for your class.
// In the case of not using mapping you would do this like this:
let name = personDictionary["name"] ?? "" // defaut value
let surname = personDictionary["surname"] ?? "" // defaut value
let fullname = "\(name) \(surname)"
fullnameLabel.text = fullname
// This will work ofc. But without mapping, you should handle any case of error at your response block, your business will be at response block.
// I gave this example, because some code reviews I did, show me the usage of this style.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment