首页 > 解决方案 > 在 Swift 5 中调用函数导致错误“表达式类型不明确,没有更多上下文”

问题描述

当调用我的函数从 API 获取一些位置时,我收到错误“表达式类型不明确,没有更多上下文”。

由于我对 iOS 开发和 swift 比较陌生,所以我不得不问你们。希望这只是我监督的一些简单的事情。我已经在网上搜索过,但没有任何帮助。

先感谢您!

这是我调用该函数的方式:

fetchLocation(latitude: latitude, longitude: longitude, locationsCompletionHandler: {
            shopSites in
            
            ForEach (shopSites){  }
            
        })

这是功能:

func fetchLocation(latitude: Double, longitude: Double, locationsCompletionHandler: @escaping ([ShopSite]) -> Void) {

    let semaphore = DispatchSemaphore (value: 0)
    
    let domain = "http://e2cadda8d178.ngrok.io/api/v1/"
    let urlString = domain + "public/location/" + String(latitude) + "/" + String(longitude) + "/50"
    
    //let url = URL(string: "e2cadda8d178.ngrok.io/api/v1/public/location/66.68994/10.249066/50")!
    let url = URL(string: urlString)!
    
    var request = URLRequest(url: url,timeoutInterval: Double.infinity)
    request.httpMethod = "GET"

    let task = URLSession.shared.dataTask(with: request) { json, response, error in
        guard let json = json else {
            print(String(describing: error))
            semaphore.signal()
            locationsCompletionHandler([])
            return
        }
        let str = String(decoding: json, as: UTF8.self)
        print(str)
        let shopSites: [ShopSite] = try! JSONDecoder().decode([ShopSite].self, from: json)
        print(shopSites.count)
        semaphore.signal()
        locationsCompletionHandler(shopSites)
    }

task.resume()
semaphore.wait()

如果您需要更多详细信息,请立即告诉我。

标签: swiftfunctionasynchronous

解决方案


我认为您的 for each 循环代码可能有问题,请尝试将您的回调代码更改为

fetchLocation(latitude: latitude, longitude: longitude, locationsCompletionHandler: {
            shopSites in
            
            for site in shopSites {

            }
            
        })

推荐阅读