簡體   English   中英

如何在 Swift 中擴展內部范圍值

[英]How can I expand inner scope value in Swift

我開始開發沒多久。 所以我的代碼有問題。 我想在TableView函數中返回data.count 但我無法在db.collection()獲取數據的值: [DataGroup] 它沒有超出db.collection()范圍的價值。 那么我怎樣才能從那個范圍內獲取數據呢?

class RecordGroupViewController: UIViewController, UITableViewDataSource {
    
    let db = Firestore.firestore()
    var data: [DataGroup] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        fetchDataGroup()
    }
    
    func fetchDataGroup() {
        
        db.collection("data").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    do {
                        let docuData = try JSONSerialization.data(withJSONObject: document.data(), options: [])
                        let decoder = JSONDecoder()
                        let groupData: DataGroup = try decoder.decode(DataGroup.self, from: data)
                        
                        self.data.append(groupData)
                    } catch let error {
                        print("---> error: \(error.localizedDescription)")
                    }
                }
            }
        }
        print("\(self.recordGroups.count)")
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
}

根據我對您的問題的理解,您想訪問數據變量的計數。

您可以使用 self.data.count 從代碼中的任何位置執行此操作

但是,如果您希望 tableView 使用此新值:

  1. 使用 IBOutlet 將您的 tableview 鏈接到您的控制器(或者如果您以編程方式對其進行實例化,則創建對它的引用)

  2. 將新數據附加到數據后,調用 self.yourTableViewReference.reloadData(),這將使 tableView 使用新附加的數據調用您的 dataSource 方法 numberOfRowsInSection。

暫無
暫無

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

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