arrays - 为什么在 swift4 中有一个数组为空和错误?

标签 arrays swift

我花了几个小时试图让 fetch 在我的胶片表中工作。我需要打开我的 collectionview 项目的电影 View 。我可以按照不同的指南发布,但它总是给我一个空数组。我是新手,很抱歉我的问题,但我需要你的帮助。

这是我的代码:

var taskArrayScheda : NewFilm?

override func viewDidLoad() {
super.viewDidLoad()

self.fetchData()

if(self.taskArrayScheda != nil) {

let schedaOk = taskArrayScheda
mostraDatiNellaScheda(schedaOk!)

} else { print("errore array vuoto") }


}

func mostraDatiNellaScheda(_ sched:NewFilm) {

// get title
titoloScheda.text = sched.titolo
}

func fetchData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext


let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "NewFilm")

do {
taskArrayScheda = try context.fetch(NewAnime.fetchRequest())
💥ERROR ::::: Cannot assign value of type '[Any]' to type 'NewFilm?'

} catch {
print(error)
}
}    

最佳答案

fetch() 返回一个数组。但目前您将 fetch() 结果分配给单个对象 var taskArrayScheda

你需要这样的东西:

var taskArrayScheda: [NewFilm]?

那么你应该这样做:

taskArrayScheda = try context.fetch(NewAnime.fetchRequest()) as? [NewFilm]

我在这里假设 NewAnimeNewFilm 的子类,从这两个类名来看似乎很有意义。

关于arrays - 为什么在 swift4 中有一个数组为空和错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54910160/

相关文章:

c - 像访问单个数组一样访问结构成员?

javascript - 使用 javascript 和 d3 上传 csv 文件

ios - 带有快速枚举作为参数的 Swift 方法在 Objective C 中不可见

ios - 类型 'UIViewController' 的值没有名为 JSON 的成员 'jsonfile'

javascript - 空数组为假,但在 IF 语句中它返回真

xcode - 从大小为 N 的数组中选择 K 个元素,使得子数组中的最小元素和最大元素之间的差异最小

Swift - 如何使动画箭头指向正确的方向?

arrays - 无法使用 Swift 4.0 将检索到的 JSON 复制到简单的整数数组中

python - 如何使用 numpy 有效地将函数应用于第三维数组?

macos - 如何在 Mac Cocoa App (Swift) 上显示进度条