【问题标题】:Accessing nested array values in swiftui?在swiftui中访问嵌套数组值?
【发布时间】:2021-05-31 12:24:06
【问题描述】:

我正在使用一个嵌套数组。

我需要访问这个嵌套数组中的一些值。

我可以使用我的代码访问根值,但不能访问嵌套值。

这是我当前的代码:

    // MARK: - Root
    struct RootD: Codable {
        let id: Int
        let books: String
        let regs: [SightingsD]
        
    
        enum CodingKeys: String, CodingKey {
            case id = "id"
            case serial = "books"
            case regs = "regs"
        }
    }
    
    
    struct SightingsD: Codable, Identifiable {
        public var id: Int
        public var regNo: String
     
    
        
        enum CodingKeys: String, CodingKey {
            case id = "id"
            case regNo = "regNo"
    
            }
    }

我可以像这样访问 Root 的东西:

          if let str = String(data: data!, encoding: .utf8) {
             
                let data = str.data(using: .utf8)!
                do {
                    if let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
                    {

                        books = jsonArray["books"] as! String

                        
                    } else {
                        print("bad json")
                    }
                } catch let error as NSError {
                    print(error)
                }

            }

但是我怎样才能访问像regNo 这样的东西呢?

【问题讨论】:

  • 你有数据,然后你把它转换成字符串,然后再转换成数据?为什么 ?直接作为Data使用

标签: ios arrays swift


【解决方案1】:

你不使用JSONDecoder

guard let data = data else { return }
  do {
       let res = try JSONDecoder().decode(RootD.self, from:data)  
       res.regs.forEach { 
           print($0.regNo)
       }
     
  } catch {
      print(error)
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2019-03-27
    相关资源
    最近更新 更多