ios - 下面的代码片段有什么区别?
问题描述
class AGResults: Codable {
let geoFencing: [ActiveGeoFencingArray]
enum CodingKeys: String, CodingKey {
case geoFencing = "geo_fencing"
}
init(geoFencing: [ActiveGeoFencingArray]) {
self.geoFencing = geoFencing
}}
和
typealias AGResults = [ActiveGeoFencingArray]
如果我使用 Class 那么它在解码时会出错:
let jsonData = try JSONSerialization.data(withJSONObject: geoFencingDic, options: .prettyPrinted)
let activeGeoFences = try newJSONDecoder().decode(AGResults.self, from: jsonData)
错误:
▿ DecodingError
▿ typeMismatch : 2 elements
- .0 : Swift.Dictionary<Swift.String, Any>
▿ .1 : Context
- codingPath : 0 elements
- debugDescription : "Expected to decode Dictionary<String, Any> but found an array instead."
- underlyingError : nil
如果我使用 typealias 那么它工作正常。
这两种方法有什么区别?
解决方案
如果您使用名为的类,AGResults
那么您的 json 应该有一个名为geo_fencing
. 如果您改用命名的 typealias AGResults
,则解码器期望解码一个数组。
typealias 就是这样 - 一个别名。所以通过这样做:
typealias AGResults = [ActiveGeoFencingArray]
您是在告诉编译器AGResults
equals [ActiveGeoFencingArray]
,基本上意味着每当您AGResults
在代码中使用时,您实际上是在指代[ActiveGeoFencingArray]
推荐阅读
- java - 案例3不会执行
- swift - Swift UICollectionViewCell UIlabel 问题
- python - send_mail() 缺少 1 个必需的位置参数:'recipient_list'
- sql-server - 有什么方法可以让 sqlserver 中的视图中的数据始终正确?
- c# - 使用 C# 中泛型类中定义的泛型参数调用泛型方法
- jquery - 从 AJAX 请求中获取响应并将其插入到传出链接中
- reactjs - 渲染对象数组
- css - Bootstrap 5.0 汉堡菜单图标不显示
- swift - 当玩家收到轮到他们的通知时 Swift 崩溃
- visual-studio - 有没有办法强制 msbuild 只构建 x64?