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
}
}