我正在尝试在Firebase上获取字符串(在对象内部)(使用Swift)


let currentDocument = db.collection("countries").document("United States")

        currentDocument.getDocument { (document, error) in
            if let document = document, document.exists {
                let cities = document.data()!["cities"] as? [AnyObject] // This grabs data from a Firebase object named `cities`, inside the object there are arrays that have two pieces of data (e.g. ["cityName" : "New York", "currentTemperature" : 38])
                for i in 0..<cities!.count {
                    let cityName = String(cities![i]["cityName"]!) // Here is where I get the error `Cannot invoke initializer for type 'String' with an argument list of type '(RemoteConfigValue)'`
                }
            } else {
                print("Document does not exist")

            }
        }



搜索此错误后,我发现的常规解决方案类似于these ones

但是,即使在应用了这些解决方案之后,例如:


if let cityName = cities![i]["cityName"]! as? String {
  print(cityName)
}



我仍然收到类似Cast from 'RemoteConfigValue' to unrelated type 'String' always fails的错误

我该如何解决?

最佳答案

请阅读documentation


  class RemoteConfigValue : NSObject, NSCopying
  
  此类为Remote Config参数值提供了包装,并提供了以不同数据类型获取参数值的方法。


所以你必须写这样的东西

if let cities = document.data()!["cities"] as? [[String:Any]] { // cities is obviously an array of dictionaries
   for city in cities { // don't use index based loops if you actually don't need the index
       if let cityName = city["cityName"] as? RemoteConfigValue {
          print(cityName.stringValue)
       }
   }
}

10-08 05:45