[英]decoding a Codable in Swift
麻煩讓它起作用:我試圖將JSON解碼抽象為一個函數,以一個Codable加上一些Data作為參數。
因此,如果可能的話,我需要具有以下功能簽名:
func doTheJSONDecoding(cdbl: Codable, data: Data) {...}
這是我的代碼,從數據模型開始。 下面有兩個示例。
import UIKit
import Foundation
struct MyStructCodable : Codable {
let items : [MyValue]?
}
struct MyValue : Codable {
let value : String?
}
let dta: Data = """
{
"items": [
{
"value": "Hello1"
}
]
}
""".data(using: .utf8)!
然后是兩個例子:
// Example 1: this code works fine !!!!!!!!!!!!!!!!!!!!!!!!
let decoder = JSONDecoder()
do {
let result = try decoder.decode(MyStructCodable.self, from: dta)
print(result.items?[0].value ?? "")
} catch {
print(error)
}
// above code prints: Hello1
// Example 2: this code does not work - WHY ???????????????
func doTheJSONDecoding(cdbl: Codable, data: Data) {
let decoder = JSONDecoder()
do {
let result = try decoder.decode(cdbl, from: data)
print(result.items?[0].value ?? "")
} catch {
print(error)
}
}
let myValue = MyValue(value: "Hello2")
let myStructyCodable = MyStructCodable(items: [myValue])
doTheJSONEncoding(cdbl: myStructyCodable, data: dta)
拋出的錯誤在函數內部,它說:
有什么辦法可以使函數簽名保持不變(即func doTheJSONDecoding(cdbl: Codable, data: Data)
並且仍然可以func doTheJSONDecoding(cdbl: Codable, data: Data)
正常工作??感謝任何幫助。
這是我嘗試使您的func正常工作的嘗試,它可能會得到改善,但確實會返回正確解碼的對象。 請注意,它采用對象的類型而不是對象,並且類型T實現了Decodable。
func doTheJSONEncoding<T: Decodable>(cdbl: T.Type, data: Data) -> T? {
let decoder = JSONDecoder()
do {
let result = try decoder.decode(cdbl.self, from: data)
return result
} catch {
print(error)
}
return nil
}
//testing it
let myValue = MyValue(value: "Hello2")
let myStructyCodable = MyStructCodable(items: [myValue])
let decoded = doTheJSONEncoding(cdbl: MyStructCodable.self, data: dta)
print(decoded?.items?[0].value ?? "")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.