gpt4 book ai didi

swift - 为什么我的词典没有添加到我的数组中? indexPath.row 返回 nil

转载 作者:行者123 更新时间:2023-11-28 13:29:28 25 4
gpt4 key购买 nike

我得到一个错误:let video = videos[indexPath.row]Unexpectedly found nil while unwrapping an optional value. 这意味着两个字典都不是在数组 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) 时添加的每个字典,但是它显示错误。

最佳答案

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

var 视频:[Video] = [Video]()

关于swift - 为什么我的词典没有添加到我的数组中? indexPath.row 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57639227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com