I am trying to make a generic function that returns objects obtained via a REST API JSON response. I want to provide the type with a generic, have it submit the request/parse the JSON, and return a list of objects of the provided type (such as Item). I have the part of getting the JSON response, but using generics is new for me. Here's a pseudocode of the situation holding me up:
class Model {
func setPropertiesFromJSON(data: NSData) {
// Lookup property names of object and set from JSON fields.
}
}
class Item : Model {
var a
var b
}
class RestEndpoint {
func getModels<T>() -> [T] {
let data: NSData = ... // Submit GET request and receive JSON data.
var models = [T]()
for objectData in data {
// How to create newobj as T (subtype of Model), set its properties,
// and add it to models array?
// let newobj: T as? TrackminiModel = T()
// newobj.setPropertiesFromJSON(objectData)
// models.append(newobj)
}
return models
}
}
let restEndpoint = RestEndPoint()
var items: [Item] = restEndpoint.getModels<Item>()
The commented out code is very incorrect but that is the goal. Any thoughts on how to do this?
From your question it sound like what your are interested in is something that is a fairly common need. The ability to communicate with a backend server using a Restful API. You can continue down the path you seem to be heading an create a lot of code to accomplish this, and this answer will not provide much help in that direction.
However I would like to point you to two open source libraries, ObjectMapper, which I think addresses your question. Here is a brief description of ObjectMapper (from its github page).
ObjectMapper is a framework written in Swift that makes it easy for you to convert your Model objects (Classes and Structs) to and from JSON.
The second project is AlamofireObjectMapper which I think in the end might be exactly what you are looking for. Here is a brief description from that projects githup page.
An extension to Alamofire which automatically converts JSON response data into swift objects using ObjectMapper.
All of this is built on top of Alamofire which handle all the details of communicating with Restful API's.
Again here is a brief description of Alamofire.
Alamofire is an HTTP networking library written in Swift.
You might feel like picking up other libraries to accomplish some task is "cheating" you out of an opportunity to learn how to do something yourself, but there are still plenty of challenges in making an app. Some would say not taking advantage of these open source libraries is "undifferentiated heavy lifting"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With