BadmintonCat
BadmintonCat

Reputation: 9576

Use generic argument in method body <T>

I'm trying to create a generic method like the following:

private func map<T>(type:T, jsonString:String) -> T
{
    do
    {
        let model = try Mapper<type>().map(JSONString: jsonString)!
        return model
    }
    catch
    {
        Log.error("Failed to convert JSON jsonString to model object: \(jsonString)")
    }
    return EmptyModel()
}

but it result in compile error: Error: use of undeclared type 'type'

How can I change it to use the specified type (a class object) with the Mapper's generic value?

Upvotes: 1

Views: 84

Answers (1)

amgalan-b
amgalan-b

Reputation: 76

You can use T instead of type:

let model = try Mapper<T>().map(JSONString: jsonString)!

You might want to change method signature, so it returns an instance of T and not the type T itself:

private func map<T>(type: T.Type, jsonString: String) -> T

That being said, Swift already has its JSONDecoder. It might already support what you are trying to implement.

let decoder = JSONDecoder()
let model = try decoder.decode(Model.self, from: data)

Upvotes: 1

Related Questions