簡體   English   中英

Swift - 參數類型不符合預期類型

[英]Swift - Argument type does not conform to expected type

我正在嘗試在我的 Swift 應用程序中制作可重復使用的 JSON 解碼器,但運行時出現以下錯誤:

  • 參數類型“User.Type”不符合預期類型“Decodable”
  • 參數類型“User.Type”不符合預期類型“Encodable”

我的代碼如下:

func decode<T: Codable>(_ type: T.Type, from: String) -> [T] {
    let url = URL(fileURLWithPath: from)
    let data = try? Data(contentsOf: url)
    let result = try? JSONDecoder().decode([T].self, from: data!)
    return result!
}
print(decode(User.self, from: "data.json")

感謝您幫助我解決這個問題。

最好的問候, NG253

如果編譯器知道返回類型,則不需要將類型作為參數傳遞

這是我的版本(使用本地字符串)

func decode<T: Decodable>(from: String) throws -> [T] {
    //let url = URL(fileURLWithPath: from)
    //let data = try? Data(contentsOf: url)
    let data = from.data(using: .utf8)!
    return try JSONDecoder().decode([T].self, from: data!)
}

struct User: Decodable {
    let name: String
}

let str = """
   [{"name": "abc"}]
"""

do {
    let users: [User] = try decode(from: str)
} catch {
    print(error)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM