arrays - 为什么 JSON 返回这样的值 2.2348142859517371e-314 和 6.9531204333502763e-310

标签 arrays json swift url

不返回解析的 json,即使它打印了。

guard let unwrappedZipcode = self.zipCode else {print("did not unwrap zipcode"); return}
        self.coordinateStore.getUserCoordintes(zipcode: unwrappedZipcode, completion: { (coordinatesJson) in
            print("********************")
            print(coordinatesJson)
            print("does this work")
            print("*******************")
            print(self.coordinateStore.locationCoordinates.first)

        })

这是进行网络调用并解析 JSON 的函数:

func getUserCoordintes (zipcode: String, completion:@escaping ([Coordinates]) -> ()){
    GoogleCoordinateAPIClient.getCoordinateInformation(zipCode: zipcode) { (googleAPICoordinatesJson) in

        guard let unwrappedJson
            = googleAPICoordinatesJson as? [String: Any] else {print("did not unwrap at the first level"); return}

        guard let secondLevelArray = unwrappedJson["results"] as? Array<Any> else {print("did not unwrap at the second level"); return}

        guard let firstElementFromArray = secondLevelArray[0] as? [String : Any] else {print("did not unwrap at the third level"); return}

        guard let geometryDictionary = firstElementFromArray["geometry"] as? [String: Any] else {print("did not unwrap at the fourth level"); return}

        guard let locationDictionary = geometryDictionary["location"] as? [String: Any] else {print("did not unwrap at the fifth level"); return}

        guard let locationLat = locationDictionary["lat"] as? Double else {print("did not unwrap latitude"); return}
        guard let locationLng = locationDictionary["lng"] as? Double else {print("did not unwrap longitude"); return}

        let coordinatesObject = Coordinates.init(latitude: locationLat, longitude: locationLng)

        self.locationCoordinates.append(coordinatesObject)

        print(self.locationCoordinates.count)

        print("*********************************")
        print(self.locationCoordinates.first?.latitude)
        print(self.locationCoordinates.first?.longitude)
        print("*********************************")
    }
    completion(self.locationCoordinates)
}

打印出 1 和坐标,但显示为空数组,其中没有任何内容。

最佳答案

您有一个异步调用。您需要在异步调用的完成 block 内调用函数的完成处理程序。

移动线:

completion(self.locationCoordinates)

就在 print 语句之后。正如您现在所看到的,您对 completion(self.locationCooperatives) 的调用早在异步调用开始之前就已经进行了。

关于arrays - 为什么 JSON 返回这样的值 2.2348142859517371e-314 和 6.9531204333502763e-310,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48978369/

相关文章:

php - 从 PHP 中的序列化数组中获取一个值

c++ - 默认初始化和值初始化结构的不同性能

ios - 当它是 Swift 中的图库图像时,如何禁用 UIImagePickerController 中的编辑选项?

ios - 执行segues到非默认选项卡 View Controller 模态不同的 Storyboard

ios - 解析字符串并在 swift 中以 Json 形式发送

php - 如何在不循环执行的情况下将数组插入mysql

javascript - 将平面数组减少为 2 层嵌套 json 对象数组

python - 将 bool 字符串值映射到 JSON 中的 true/false

python - 使用返回 KeyError 的 Pandas 扁平化 JSON

javascript - 迭代数组并对每个元素求和 1