Swift初始化类并使用参数和方法

问题描述

我是新来的人,我的问题对大多数人来说可能是傻瓜。但是我尝试通过实践来学习的任何方式。这是我的问题。 我有一个模特:

import Foundation
import Firebase

struct special {
    let name: String
    let position: Int
    let imageURL: String?
}


class SpecialList {
    
    var specialList: [special] = []

    init() {        
        
    }
    
    func loadSpecial () {
        db.collection("special").getDocuments { (querySnapshot,error) in
            if let e = error {
                print("Error\(e)")
            } else {
                if let snapshotDocuments = querySnapshot?.documents {
                    for doc in snapshotDocuments {
                        let data = doc.data()
                        if let name = data["name"] as? String,let position = data["position"] as? Int,let imageURL = data["imageURL"] as? String {
                            let newList = special(name: name,position: position,imageURL: imageURL)
                            self.specialList.append(newList)
                        }
                    }
                }
            }
        }
    }    
}

我正在尝试在ViewController中实现它:

var specialList = SpecialList()

override func viewDidLoad() {
specialList.loadSpecial()
print(specialList.specialList)
}

实际上,我需要的是从firebase检索的数据。我正在尝试将其保存在var specialList: [special] = []中,但始终为空。我认为我应该在init()中做些事情,但没有找到正确的方法

P.S。从firebase加载工作正常。检查是否已打印数据。

,数据应位于collectionView

func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return specialList.specialList.count
    }
    
    func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SpecialCell",for: indexPath as IndexPath) as! SpecialCollectionViewCell
        
        if let imageURL = specialList.specialList[indexPath.row].imageURL {
            let url = URL(string: imageURL)
            cell.specialPic.kf.setimage(with: url) // download foto
        }
        cell.specialName.text = specialList.specialList[indexPath.row].name
        return cell
    }

解决方法

func loadSpecial (completion: @escaping (Bool) -> Void) {
    db.collection("special").getDocuments { (querySnapshot,error) in
        if let e = error {
            print("Error\(e)")
            completion(false)
        } else {
            if let snapshotDocuments = querySnapshot?.documents {
                for doc in snapshotDocuments {
                    let data = doc.data()
                    if let name = data["name"] as? String,let position = data["position"] as? Int,let imageURL = data["imageURL"] as? String {
                        let newList = special(name: name,position: position,imageURL: imageURL)
                        self.specialList.append(newList)
                    }
                }
                completion(true)
            }
            completion(false)
        }
    }
}

向您的方法添加完成

在VC中执行

override func viewDidLoad() {
    super.viewDidLoad()
    specialList.loadSpecial(completion: { [weak self] success in
        self.collectionView.reloadData()
    })
}

如果集合实现正确,您将看到

,

在您的append语句和print语句中放置一个断点,看看哪个首先被调用。在获取数据之前,可能会调用print语句。

,

如果有人遇到相同的问题。解决方案的最佳方法是使用委托。我添加了额外的内容:

protocol SpecialListUpdateDelegate {
    func didUpdate(sender: SpecialList)
}

在我的班上SpecialList:

var delegate: SpecialListUpdateDelegate?

在loadspecial()中:

self.delegate?.didUpdate(sender: self)

在VC的VC添加协议中:SpecialListUpdateDelegate

在viewDidLoad中:

specialList.delegate = self

和最后一个实现功能:

func didUpdate(sender: SpecialList) {
        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }
    }