【问题标题】:How to map an array in a Firestore document to Swift?如何将 Firestore 文档中的数组映射到 Swift?
【发布时间】:2022-01-11 20:29:33
【问题描述】:

如何将以下 Firestore 文档中的数组映射到 Swift?

这是我在 Swift 中的数据模型:

  import Foundation
    
  struct CityList: Codable, Hashable {
    var name: String
    var latitude: String
    var longitude: String
  }
    
  struct Cities: Codable, Identifiable {
    var id: String = UUID().uuidString
    var citiesList: [CityList]
  }

这是我的视图模型:

class WeatherList: ObservableObject {

  @Published var cities = [CityList]()
    
  func fetchCities(userInfo: UserInfo) {
    self.cities.removeAll()
    
    let db = Firestore.firestore()
      .collection("cities")
      .document(userInfo.user.uid)
       
    db.getDocument() { (document, error) in
      if let document = document, document.exists {
        guard let itemIDs = document.get("citiesList") else { 
          return 
        }
        for i in itemIDs {
          print(i.value)
        }
      } 
      else { 
        return 
      }
    }
  }
}

执行时显示错误:Protocol 'Any' as a type cannot conform to 'Sequence'

如何映射此文档?

【问题讨论】:

  • 您还没有将文档数据转换为 CityList - 请查看文档中有关自定义对象的部分:firebase.google.com/docs/firestore/query-data/…
  • 与您的问题无关,但我很好奇:您的城市收藏中是否有多个文档?为什么选择一系列城市而不是每个城市一个文档?

标签: swift firebase google-cloud-firestore swiftui


【解决方案1】:

您就快到了,只需致电data(as:) 执行映射即可。

这是更新后的代码:

import Foundation
    
struct City: Codable, Hashable {
  var name: String
  var latitude: String
  var longitude: String
}
    
struct Cities: Codable, Identifiable {
  @DocumentID var id: String?
  var cities: [City]
}
class WeatherViewModel: ObservableObject {
  @Published var cities = [City]()

  func fetchCities(userInfo: UserInfo) {
    let docRef = Firestore.firestore()
      .collection("cities")
      .document(userInfo.user.uid)


    docRef.getDocument { document, error in
      if let error = error as NSError? {
        self.errorMessage = "Error getting document: \(error.localizedDescription)"
      }
      else {
        if let document = document {
          do {
            let citiesDocument = try document.data(as: Cities.self)
            self.cities = citiesDocument.cities
          }
          catch {
            print(error)
          }
        }
      }
    }
  }
}

如需全面了解如何将 Firestore 数据映射到 Swift 或从 Swift 映射,请查看我的博文 Mapping Firestore Data in Swift - The Comprehensive Guide

【讨论】:

    猜你喜欢
    • 2020-04-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多