首页 > 解决方案 > 在swiftui中访问嵌套数组值?

问题描述

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

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

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

这是我当前的代码:

    // 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

标签: iosarraysswift

解决方案


你不使用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)
  }

推荐阅读