【问题标题】:Map specific element to array from array of codable classes将特定元素从可编码类数组映射到数组
【发布时间】:2021-06-26 03:55:07
【问题描述】:

Gallery 是以下模型中ProviderGallery 的数组。我正在尝试在不使用 forloop 的情况下将 ProviderGallery 的特定变量提取到数组中。下面的代码我使用 for 循环来获取所需的元素。

型号:

struct ProviderProfileData : Codable{
     let message : String?
    let gallery : [ProviderGallery]?
    
  }
    
    struct ProviderGallery : Codable {
        let id : Int?
        let file_name : String?
        let thumb : String?
        let mime_type : String?
        let duration : String?
        let size : String?
    }

JSON解码器:

 do {
      let decoder = JSONDecoder()
      let providerProfileDetails = try decoder.decode(ProviderProfileData.self, from: data)
      print("data \(providerProfileDetails)")

      // Here i am getting desired value into array using forloop 
      
          if let gallery = providerProfileDetails.data.gallery {
                    
                    var thumbArray = [String]()
                    
                    for i in 0..<gallery.count{
                        thumbArray.append(gallery[i].thumb ?? "")
                    }
                    print("thumbs \(thumbArray)")
                }
                




     }catch let error {
                    print("Error \(error.localizedDescription)")
     }

【问题讨论】:

    标签: ios json swift codable


    【解决方案1】:

    使用 compactmap 删除所有 nil 值或使用 map 替换 nil 值:

       let thumArray = gallery.compactMap({ return $0.thumb })
       let thumArray = gallery.map({ return $0.thumb ?? ""})
    

    【讨论】:

    • 吹毛求疵,但也许你应该使用“替换”而不是“跳过”
    猜你喜欢
    • 1970-01-01
    • 2020-12-24
    • 2010-12-04
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    相关资源
    最近更新 更多