WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Error -- Generic parameter 'T' could not be inferred?

Forums > SwiftUI

Hi. Help i cant understand.

class NewsViewModel: ObservableObject {

    @Published var news: [Card] = []
    @Published var isCard: Bool = false

    let getJson: GetJson = GetJson()

    let getData: DataFetcherService = DataFetcherService()

    func onAppear(completion: () -> Void) {
        print("launch news view!")
        self.getJson.getData(url: Urls.new.rawValue) { news, error in     ------  Generic parameter 'T' could not be inferred  😭
            print("error")
        }

    }
}

import Foundation

protocol GetDataFeatch {

    typealias news = (NewsModel?, String?) -> Void

    func getData(url: String, data: (NewsModel?, String?) -> Void)

}

class GetJson: GetDataFeatch {

    let requestData: RequestData = RequestData()
    typealias news = (NewsModel?, String?) -> Void

    func getData<T>(url: String, data: (T?, String?) -> ()) where T : Decodable {
        self.getData(url: url) { news, error in
            return data(news, nil)
        }
    }
}

   

Somewhere in your code you very precisely define a function named getData

Here's your definition:

func getData<T>(url: String, data: (T?, String?) -> ()) where T : Decodable { // details removed }

You’re telling Swift that at some point you will want to call getData, where it retrieves objects of type Cars. In another part of the app you may call getData and retrieve objects of type BroadwayShows.

In short, you are saying getData should work with any Type (shorthand “T”) as long as that type conforms to the Decodable protocol.

But when you use the getData function in code, you have to provide a hint to the compiler. I think you’re missing the hint and Swift tries, but fails, to guess (infer) the data type.

Try this?

// Use my cool getData function!  Provide a hint!
self.getJson.getData<Card>(url: Urls.new.rawValue) { news, error in 
            print("error")
        }

Nota bene: fetch! not featch.

   

Other observations


Your question was about generics and inferred types. I tried to answer that question. But your code looks like you're attempting to grab and decode JSON data from a URL.

I didn't spend any time trying to sort out your logic. But just wanted to mention that I think there are other, possibly cleaner implementations of collecting and parsing JSON data from urls. @twoStraws has some great tutorials on this.

   

Here are some simple examples to try in Playgrounds. You are using Playgrounds, right?

Paste into Playgrounds:

// Simple struct of type T
struct Card<T> where T : Decodable {
// T can be ANY type, Integer, boolean, String, Movies as long at the type is Decodable
    var name: T    
    var count = 100
}

// Define a complex data type. Make sure it conforms to Decodable
struct FullName: Decodable {
    var first = "Taylor"
    var last  = "Swift"
    var age   = 28
}

// Make some Card objects with names of different types.
let stringCard   = Card(name: "Obelix", count: 100)            // Infer the type
let fullNameCard = Card<FullName>(name: FullName(), count: 42) // Declare the type
let intCard      = Card<Int>(name: 1, count: 10)               // Declare the type

// Show me the data!
stringCard.name
fullNameCard.name.last
intCard.name

Please note! The letter T is just a convention to indicate Type. You may use any name that suits you.

For example, you could define the Card struct like so:

// Simple struct of type anyDecodableTypeInMyApplication
struct Card<anyDecodableTypeInMyApplication> where anyDecodableTypeInMyApplication : Decodable {
    var name: anyDecodableTypeInMyApplication
    var count = 100
}

   

Thanks for the help. I'll try to figure it out.

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.