簡體   English   中英

Swift 5:轉義閉包捕獲“inout”參數

[英]Swift 5 : Escaping closure captures 'inout' parameter

我已經有了從服務器收到的響應數據。 這個響應數據有一些面包師數據。

現在我想計算用戶和面包店的距離,然后將其存儲在同一個模態類中。 我為它創建了一個函數。 由於這個功能需要在 4,5 視圖控制器中使用,我的計划是創建作為 UIViewController 的擴展

func getDistanceUserBakery(bakeryData : inout [BakeryRecord], completion : @escaping (Int?) -> () ) {

    for index in 0...(bakeryData.count-1) {
        //1
        let googleApiAdd = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&"
        //2
        let origin = "origins=\(UserLocation.coordinates.latitude),\(UserLocation.coordinates.longitude)"
        //3
        let destination = "&destinations=\(bakeryData[index].location?.coordinates?[1] ?? 0.0),\(bakeryData[index].location?.coordinates?[0] ?? 0.0)"
        //4
        let googleKey = "&key=\(GOOGLE_KEY)"
        //5
        let url = googleApiAdd + origin + destination + googleKey

        let request = URLRequest(url: URL(string: url)!)

        //6 - this line is showing the error.

        let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
            guard let data = data else {
                completion(nil)
                Toast.show(message: "Unable to calculate distance from user to bakery", controller: self)
                return }
            let stringResponse = String(data: data, encoding: .utf8)!
            let dictData = stringResponse.convertToDictionary()
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: dictData as Any, options: .prettyPrinted)
                let decoder = JSONDecoder()
                let model = try decoder.decode(GoogleDistance.self, from: jsonData)
                bakeryData[index].disanceInMiles = model.rows?[0].elements?[0].distance?.text ?? "NaN"
                completion(index)
            } catch let parsingError {
                print("Error data :", parsingError)
                completion(nil)
            }
        }
        task.resume()
    }

這是我從服務器收到數據后調用此函數的方式,

  self.getDistanceUserBakery(bakeryData: &self.bakeryData) { index in
                    if index != nil {
                        DispatchQueue.main.async {
                            // here I am thinking as the bakeryData will hold the new value for distanceInMiles, the collectionView will start showing up that result on reload.
                            self.resultCollection.reloadItems(at: [IndexPath(item: index!, section: 0)])
                        }
                    }
                }

現在的問題:

據我所知,當您將參數作為 inout 傳遞時,可以從函數內部更改值,這些更改反映在函數外部的原始值中。

但是當我嘗試代碼時,它說轉義閉包捕獲 'inout' 參數 'bakeryData' 在我的代碼中,//6 產生了錯誤。

如何修復此錯誤?

正如@Paulw11 在評論中建議的那樣,

BakeryData 是一個結構體嗎? 如果是這樣,那么只需將其設為一個類。 如果您將 BakerData 設為類,則該數組包含引用類型,您可以更新元素的屬性

我將結構更改為類,它確實有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM