0

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)
1
  • 1
    change method declaration to func makeJSONData<T: Codable>(_ value: T) -> Data Commented Jan 29, 2018 at 5:10

1 Answer 1

2

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

makeJSONData<T>

to

makeJSONData<T: Codable>
Sign up to request clarification or add additional context in comments.

2 Comments

By following Mukesh`s answer, it worked. Quoc Nguyen, there is a typo on your commend.
@RenanAguiar yeah, fixed it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.