Попробуйте:
class request: NSObject {
var request: String?
var name: String?
var longitude: String?
var latitude: String?
init (dictionary: [String: Any]) {
super.init()
name = dictionary["name"] as? String
longitude = dictionary["longitude"] as? String
latitude = dictionary["latitude"] as? String
}
}
Но есть и лучшие способы десериализации.Взгляните на Codable.
Вот пример, который дает вам возможность подумать о том, как двигаться вперед:
//Codable protocol is for both Encoding & Decoding
struct Location: Codable {
let name: String
let longitude: String
let latitude: String
}
//Encode to json format from struct
let location = Location(name: "my location", longitude: "-94.420307", latitude: "44.968046")
if let encoded = try? JSONEncoder().encode(location) {
if let encodedJSON = String(data: encoded, encoding: .utf8) {
print(encodedJSON)
//Prints: {"name":"my location","longitude":"-94.420307","latitude":"44.968046"}
}
}
//Decode from json data to struct
let jsonStr = """
{
\"name\": \"my location\",
\"longitude\": \"-94.420307\",
\"latitude\": \"44.968046\"
}
"""
//jsonData is of type Data? which is generally what comes back from http request.
if let jsonData = jsonStr.data(using: .utf8) {
if let decoded = try? JSONDecoder().decode(Location.self, from: jsonData) {
print(decoded.name, decoded.longitude, decoded.latitude)
//Prints: "my location -94.420307 44.968046"
}
}