Home > database >  unespected Generic parameter 'T' could not be inferred error using generics
unespected Generic parameter 'T' could not be inferred error using generics

Time:09-22

testing some code from HakingWithSwift.com

I'd like to make generic extension on FileManager, everything ok with encoding, but I got error with myDecoding func:

Generic parameter 'T' could not be inferred

here how I call those functions

do {
    _ = FileManager.default.MyEncode(fileName: "message.txt", data: "my message")
    }
                
FileManager.default.myDecode(fileName: "message.txt")

here my entire extension

extension FileManager {
    
    
    private func getDocumentsDirectoryPath() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
    
    
    func MyEncode<T: Codable>(fileName: String, data: T) -> T? {
        let url = getDocumentsDirectoryPath().appendingPathComponent(fileName)
        let encoder = JSONEncoder()
        
        do {
            let encoded = try encoder.encode(data)
            
            do {
                try encoded.write(to: url) 
                do {
                    let input = try String(contentsOf: url)
                        print("letto: \(input)")
                    } catch {
                        print("❌ no imput: \(error.localizedDescription)")
                    }
                
                print("✅ encoded ok")
            } catch {
                print("❌ write failed: \(error.localizedDescription)")
            }
        } catch {
            print("❌ encoded failed: \(error.localizedDescription)")
            
        }
        return nil
    }
    
    func myDecode<T: Codable>(fileName: String) -> T? {
        
        let url = getDocumentsDirectoryPath().appendingPathComponent(fileName)
        let decoder = JSONDecoder()
        
        do {
            let savedData = try Data(contentsOf: url)
            do {
                let decodedData = try decoder.decode(T.self, from: savedData)
                print("✅ decoded ok")
                return decodedData
            } catch {
                print("❌ decoding failed: \(error.localizedDescription)")
            }
        } catch {
            print("❌ no data at url: \(error.localizedDescription)")
        }
        
        return nil
    }
}

CodePudding user response:

I mean the error message kinda says it all.

How would Swift know what type to decode that to? You need to specify that because Decoding depends on the actual type it wants to decode

You can specify the type like this. Just replace T with the Type you are expecting. String, or whatever

let data: T = FileManager.default.myDecode(fileName: "message.txt")
  • Related