Существует несколько причин, по которым переменная count не обновляется в функции numberOfSections.
- Count - это Int, что делает его типом значения, что означает, что в замыкании делается копияпоэтому счетчик внутри замыкания отличается от счетчика вне замыкания.
- Выборка из базы данных является асинхронной, что означает, что счетчик будет возвращен и выйдет из области видимости до выполнения замыкания.
Попробуйте, чтобы увидеть, работает ли он.
// this variable now lives beyond the scope of the function
var sectionCount: Int = 0
// fetch every time you come into this screen,
// so pushing and popping new screens on top of this one
// will update it
override func viewWillAppear() {
super.viewWillAppear()
// make your async call to your db
let firebase = ref.child("Menu").child("Category").child("Cookies")
// remember to weak reference 'self' to avoid retain cycles
getCount(ref: firebase) { [weak self] (myCount) in
// update the section count
self?.sectionCount = myCount
// tell the table view to update itself, this will tell it
// to call numberOfSections, cellForIndex, and other functions
// to update the table view
self?.tableView.reloadData()
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return self.sectionCount
}