Renan Aguiar
Renan Aguiar

Reputation: 245

Swift - JSONEncoder on generics

How can I send generic struct to a function that returns a JSON?

Im trying to make a func that gets a struct as a parameter and returns a JSON data. Im making it because I want to avoid repetition and it will be used in several places and with different structs (ie: user, client, contact...)

struct User : Codable {
    let email: String
    let password: String
}

func makeJSONData<T>(_ value: T) -> Data {
    var jsonData = Data()
    let jsonEncoder = JSONEncoder()

    do {
        jsonData = try jsonEncoder.encode(value)
    }
    catch {
    }
    return jsonData
}

By using makeJSONData, I get an error: Argument type 'T' does not conform to expected type 'Encodable'

let user = User(email: emailTextField.text!, password : passwordTextField.text!)
let user2 = makeJSONData(user)

Upvotes: 0

Views: 1639

Answers (1)

Quoc Nguyen
Quoc Nguyen

Reputation: 3007

because of you don't define the type of T, just change

makeJSONData<T>

to

makeJSONData<T: Codable>

Upvotes: 2

Related Questions