如何解决GooglePlaces API findAutocompletePredictions中NSArray元素未能匹配Swift Array元素类型?

问题描述 投票:0回答:1

我在分析GooglePlaces API的回调所给出的结果时遇到了麻烦。GMSPlacesClient findAutocompletePredictionsFromQuery:,这是一个GMSAutocompletePrediction数组。

该应用程序将在以下情况下崩溃 let searchResultsWayPoints = finalResults.map 指出

Precondition failed: NSArray element failed to match the Swift Array Element type
Expected GMSAutocompletePrediction but found GMSAutocompletePrediction
func getGoogleWayPoint(text: String) -> Promise<[GoogleWayPoint]> {
        return Promise<[GoogleWayPoint]> { resolver in
            if text.isEmpty {
                resolver.fulfill([])
                return
            }
            placesClient.findAutocompletePredictions(fromQuery: text, filter: filter, sessionToken: sessionToken) { (results, error) in
                if let error = error {
                    dprint(error.localizedDescription)
                    resolver.fulfill([])
                    return
                }


                guard let finalResults = results else {
                    dprint("can't found results")
                    resolver.fulfill([])
                    return
                }
                let searchResultsWayPoints = finalResults.map {
                    GoogleWayPoint(id: $0.placeID, address: $0.attributedFullText.string)
                }
                resolver.fulfill(searchResultsWayPoints)
            }
        }
    }

希望得到任何帮助。谢谢您的帮助。

google-places-api swift5
1个回答
0
投票

所以,我已经解决了这个问题,但我没有修复任何东西,因为它是从GooglePlaces框架。

为了解决这个问题,简单地使 results 作为 results:[Any]? 在回调时。

然后,在 guard let,安全地将其转换为 [GMSAutocompletePrediction].

以下是完整的代码

func getGoogleWayPoint(text: String) -> Promise<[GoogleWayPoint]> {
        return Promise<[GoogleWayPoint]> { resolver in
            if text.isEmpty {
                resolver.fulfill([])
                return
            }
            placesClient.findAutocompletePredictions(fromQuery: text, filter: filter, sessionToken: sessionToken) { (results: [Any]?, error) in
                if let error = error {
                    dprint(error.localizedDescription)
                    resolver.fulfill([])
                    return
                }


                guard let finalResults = results as? [GMSAutocompletePrediction] else {
                    dprint("can't found results")
                    resolver.fulfill([])
                    return
                }
                let searchResultsWayPoints = finalResults.map {
                    GoogleWayPoint(id: $0.placeID, address: $0.attributedFullText.string)
                }
                resolver.fulfill(searchResultsWayPoints)
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.