我有一个通过 API 调用接收到的 json 对象的命名数组。
{
"Images": [{
"Width": 800,
"Height": 590,
"Url": "https://obfuscated.image.url/image1.jpg"
}, {
"Width": 800,
"Height": 533,
"Url": "https://obfuscated.image.url/image2.jpg"
}, {
"Width": 800,
"Height": 478,
"Url": "https://obfuscated.image.url/image3.jpg"
}]
}
这些对象是 Image 类型,我已经定义了它,并且有一个可以解码单个 Image 对象的解码函数。图像看起来像:
struct Image : Codable {
let width: CGFloat
let height: CGFloat
let url: String
enum ImageKey: String, CodingKey {
case width = "Width"
case height = "Height"
case url = "Url"
}
init(from decoder: Decoder) throws
{
let container = try decoder.container(keyedBy: ImageKey.self)
width = try container.decodeIfPresent(CGFloat.self, forKey: .width) ?? 0.0
height = try container.decodeIfPresent(CGFloat.self, forKey: .height) ?? 0.0
url = try container.decodeIfPresent(String.self, forKey: .url) ?? ""
}
func encode(to encoder: Encoder) throws
{
}
}
我为这种情况写了一个测试,但这就是我难住的地方!测试失败(自然),看起来像这样:
func testManyImages() throws {
if let urlManyImages = urlManyImages {
self.data = try? Data(contentsOf: urlManyImages)
}
let jsonDecoder = JSONDecoder()
if let data = self.data {
if let _images:[Image] = try? jsonDecoder.decode([Image].self, from: data) {
self.images = _images
}
}
XCTAssertNotNil(self.images)
}
我的问题是这样的:
如何通过名称“图像”或其他方式访问图像数组?
感谢您的阅读,一如既往地感谢您的帮助。