首页 > 解决方案 > 下面的代码片段有什么区别?

问题描述

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 那么它工作正常。

这两种方法有什么区别?

标签: iosswift

解决方案


如果您使用名为的类,AGResults那么您的 json 应该有一个名为geo_fencing. 如果您改用命名的 typealias AGResults,则解码器期望解码一个数组。

typealias 就是这样 - 一个别名。所以通过这样做:

typealias AGResults = [ActiveGeoFencingArray]

您是在告诉编译器AGResultsequals [ActiveGeoFencingArray],基本上意味着每当您AGResults在代码中使用时,您实际上是在指代[ActiveGeoFencingArray]


推荐阅读