I am having an error in mapping my json data to the model, so I decided to keep the variables of model class to Any?. But I am not sure whether it's programmatically correct to keep all or some of your model values to Any data type.
Asked
Active
Viewed 34 times
-2
-
Using Any is not a good solution, it's better to solve the underlying problem instead. – Joakim Danielson Oct 07 '19 at 08:41
1 Answers
0
What you'll likely have to do is when converting from JSON to Foundation types, have the type's values be of Any
type. For example:
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as! [String:Any] else {
return
}
You'll then have to test the type of the value received and handle each situation appropriately:
guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as! [String:Any] else {
return
}
switch jsonObject["key"] {
case let int as Int:
//Handle Int scenario
case let string as String:
//Handle String scenario
case let bool as Bool:
//Handle Bool scenario
case let array as Array:
//Handle array scenario
case nil:
//Handle null scenario
default:
//Other type?
}
You could then have a property of type Any
in your model that will be cast to a certain type at a later point. Similarly, you could have multiple optional properties for each type. For example, your model could have the following properties:
class MyModel {
var int: Int?
var string: String?
var bool: Bool?
var array: Array?
}
And then, for each instance of this model, only one of these four optional properties will ever actually be set. Then later on you would, of course, check and handle for each scenario.

David Chopin
- 2,780
- 2
- 19
- 40
-
1If only one of the fields of `MyModel` would ever be set, then a `class` would be an inappropriate choice. An `enum` is a perfect fit. And btw, you can write out type-casting `if let`/`else if let`/`else` ladders as `switch` statements (`case let i as Int: ...`). Looks much tidier – Alexander Oct 07 '19 at 01:06
-
Interesting, I've never encountered type-casting in a switch statement (I'm still a student), thanks for the suggestion! – David Chopin Oct 07 '19 at 01:10
-
1Note: in your edited answer, your switch case is only checking types, and never actually casting. See https://stackoverflow.com/a/38980478/3141234 – Alexander Oct 07 '19 at 01:51
-