为什么不将我的字典添加到数组中? indexPath.row返回nil

时间:2019-08-24 15:17:12

标签: swift

我遇到错误:let video = videos[indexPath.row] 在展开一个可选值时意外发现nil。这意味着两个字典都不在数组videos中。

我认为在将字典添加到数组之前,它可能试图获取indexPath.row,因此我从viewDidLoad删除了该代码,并将其放在tableView的顶部。那没有用,所以我猜测定义数组var videos: [Video]的方式一定有问题,或者将数据设置为数组self.videos.append(video)的方式有问题。我知道video有数据,因为我打印了video.namevideo.link并给出了正确的数据。

import UIKit
import AVKit
import FirebaseCore
import FirebaseFirestore

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!


    var player = AVPlayer()
    var playerViewContoller = AVPlayerViewController()
    var db: Firestore!
    var videos: [Video]!

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell", for: indexPath) as! VideoTableViewCell

        let video = videos[indexPath.row] // unexpectedly found nil
        cell.video = video
        return cell

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self

        db = Firestore.firestore()

        db.collection("videos").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    let docRef = self.db.collection("videos").document(document.documentID)
                    docRef.getDocument { (document, error) in
                        if let video = document.flatMap({
                            $0.data().flatMap({ (data) in
                                return Video(dictionary: data)
                            })
                        }) {
                            self.videos.append(video)

                        } else {
                            print("Document does not exist")
                        }
                    }

                }
            }
        }

    }

}


public struct Video {

    let name: String
    let link: String

    init?(dictionary: [String: Any]) {
        self.name = dictionary["name"] as! String
        self.link = dictionary["link"] as! String
    }
}

该代码运行videos时,应该在数组self.videos.append(video)上添加我所添加的每个字典,但是显示错误。

1 个答案:

答案 0 :(得分:1)

您不能追加到nil数组。首先将其定义为空的视频数组。

var videos: [Video] = [Video]()