简体   繁体   English

在 Swift 中改变结构属性类型

[英]Mutating struct property types in Swift

I call an api and depending on the parameters I pass on the call it either returns a [Standings] or a [[Standings]] .我调用一个 api,根据我在调用中传递的参数,它返回[Standings][[Standings]] However this is done dynamically depending on the user preferences and tableView didSelectRow.然而,这是根据用户偏好和 tableView didSelectRow 动态完成的。 The endpoint is the same for all calls within the specific "click" and the rest of the struct remains the same.对于特定“点击”内的所有调用,端点都是相同的,结构的其余部分保持不变。 Is there a way to decode this one in run time?有没有办法在运行时解码这个?

 struct League: Codable {
    let standings: [Standing]?
...
}

Maybe you can create 2 struct :也许您可以创建 2 个 struct :

struct League: Codable {
    let standings: [Standing]?
     ...
}

struct StandingsLeague: Codable {
    let standings: [[Standing]]?
    ...
}

And depending on "depending on the parameters I pass on the call" parse the structure you need.并根据“取决于我在调用中传递的参数”解析您需要的结构。 Or you can through do-catch:或者你可以通过 do-catch:

do {
   let parserResult = try decoder.decode(League.self, from: data)
} catch {
  do {
     let parserResult = try decoder.decode(StandingsLeague.self, from: data)
  catch {
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM