簡體   English   中英

在 Swift 中更新變量之前,數組正在更新

[英]Array is updating before variables are updated in Swift

我正在嘗試從 Firestore 獲取玩具列表並將其放入數組但是當我調用 function 時,它返回空數組,並且在返回后立即打印玩具 object,因此順序被破壞。

我認為閉包會對我有所幫助,但我認為我不知道如何使用它們,並且來自 Google 的示例對我沒有幫助

這是我的代碼(我使用 SwiftUI 所以我創建了帶有變量的 swift 文件)

let db = Firestore.firestore()
class DataLoade {
    func loadFirebase(completionHandler: @escaping (_ toys: [Toy]) -> ()){
        var toysar: [Toy] = []
        let toysRef = db.collection("Toys")
        toysRef.getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    var name: String = document.get("name") as! String
                    var id: Int = document.get("id") as! Int
                    var description: String = document.get("description") as! String
                    var imageName: String = document.get("imageName") as! String
                    var price: String = document.get("price") as! String
                    var category: String = document.get("category") as! String
                    var timeToy = Toy(id: id, name: name, imageName: imageName, category: category, description: description, price: price)
                    toysar.append(timeToy)


                }




            }
        }

        completionHandler(toysar)
    //    print(toysar)

    }




}


這就是它打印出來的內容:

[] // it prints empty array, but it  is in the end of the code
Toy(id: 1001, name: "Pikachu", imageName: "pikachu-plush", category: "lol", description: "kek", price: "350₽") // and now it prints Toy object, however it is in the start of the code 

好的,所以我嘗試為我的 function 制作完成處理程序,就像在“重復”答案中一樣,但這不起作用:數組在完成處理程序工作之前返回

ContentView.swift  
func updateArray() -> [Toy]{
    dl.loadFirebase() { toys in
            ll = toys

            }
    print("lol \(datas)") // prints «lol []»
    return ll
}

您可以使用DispatchGroup等待異步任務。 但訣竅是不要將異步任務與return語句相關聯。 相反,在任務完成后使用closures來執行操作。 免責聲明:我在 SO 上寫了這個,我提前為語法問題道歉。

let toyData = loadFirebase( { (toys) in
    print(toys)
    //Do something with toys when done
    //You could add another completionHandler incase it fails. 
    //So 1 for pass and 1 for fail and maybe another for cancel. W/e u want
} )
let db = Firestore.firestore()

func loadFirebase(completionHandler:@escaping ((toys: [Toy]?) -> Void)) {
    //Create Group
    let downloadGroup = DispatchGroup()
    var toysar: [Toy] = []
    let toysRef = db.collection("Toys")
    //If you had multiple items and wanted to wait for each, just do an enter on each.
    downloadGroup.enter()
    toysRef.getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                var name: String = document.get("name") as! String
                var id: Int = document.get("id") as! Int
                var description: String = document.get("description") as! String
                var imageName: String = document.get("imageName") as! String
                var price: String = document.get("price") as! String
                var category: String = document.get("category") as! String
                var timeToy = Toy(id: id, name: name, imageName: imageName, category: category, description: description, price: price)
                toysar.append(timeToy)
                print(timeToy)
            }
        //We aren't done until AFTER the for loop, i.e., each item is grabbed.
        downloadGroup.leave()
        }
    }
    //Once the queue is empty, we notify the queue we are done
    downloadGroup.notify(queue: DispatchQueue.main) {
        completionHandler(toys)
    }
}
import SwiftUI
var dl = DataLoade()
var ll: [Toy] = []

let semaphore = DispatchSemaphore(value: 1)
struct ContentView: View {
    var items: [Toy]
    var body: some View {

        NavigationView{
        ScrollView(){
            VStack(alignment: .leading){
        ToyRow(category: "Наш выбор", toys: items)

            Spacer()
            ToyRow(category: "Акции", toys: items)


            }
            }.navigationBarTitle(Text("Игрушки г.Остров"))}


    }
}
func upe(completionHandler:@escaping ((toys: [Toy]?){
    dl.loadFirebase(completionHandler: { toy in
        ll.append(contentsOf: toy!)
        completionHandler(ll)
    } )
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        upe(completionHandler: { (toys) in 
            DispatchQueue.main.async {
                ContentView(items: toys)
            }
        })
    }
}

暫無
暫無

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

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