測驗來自 HakingWithSwift.com 的一些代碼
我想在 FileManager 上進行通用擴展,編碼一切正常,但 myDecoding 函式出錯:
無法推斷通用引數“T”
在這里我如何呼叫這些函式
do {
_ = FileManager.default.MyEncode(fileName: "message.txt", data: "my message")
}
FileManager.default.myDecode(fileName: "message.txt")
這是我的整個擴展
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
}
}
uj5u.com熱心網友回復:
我的意思是錯誤資訊有點說明了一切。
Swift 怎么知道將它解碼成什么型別???您需要指定,因為解碼取決于它要解碼的實際型別
您可以像這樣指定型別。只需替換T為您期望的型別。String, 管他呢
let data: T = FileManager.default.myDecode(fileName: "message.txt")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510460.html
標籤:迅速仿制药可编码
