PiratM PiratM - 1 year ago 72
Swift Question

How to pass a class type, that conforms to protocol

I'm trying to make a generic sterilizer function using SwitfyJson.
Currently every where I'm getting server response, I'm parsing is like this:

let json = JSON(data : networkResponse.data!)
let usersJson = json["data"]
var users = [User]()

for (_,subJson):(String, JSON) in usersJson {
let user = User(json: subJson)

Now this is repeatedly every were I'm getting a response.
I'm trying to use a generic function insted. It should look somthing like this:

protocol Serializable {
init(json: JSON)

func serializeToArray(data: NSData, serializable: Serializable)->serializable {

let json = JSON(data : data)
let jsonObjects = json["data"]
var serializedObjects = [serializable.classType]()

for (_,subJson):(String, JSON) in jsonObjects {
let serializedObject = User(json: subJson)

return serializedObjects

But this "classType" is not available in Swift.
Is there a way I can achieve this?

Answer Source

You can make your serialize-method use a generic type. It looks like you only need the type of the array.

func serializeToArray<SerializableType : Serializable>(data: NSData, serializableType:  SerializableType.Type)-> [SerializableType] {
    // stuff
    var serializedObjects = [SerializableType]()
    // more stuff
    return serializedObjects

This way, you can pass your type to the function without needing to instantiate an object first:

let users = serializeToArray(data: data, serializableType: User.self)

The returned result will then be of the type [User]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download