gpt4 book ai didi

swift - 对实体数组执行 `map` 时获取 nil 值

转载 作者:行者123 更新时间:2023-11-30 10:35:59 26 4
gpt4 key购买 nike

我在 iOS 应用程序中使用 Core Data 并执行以下 Swift 代码,这会导致第二行出现错误:

let movies = (try? container.newBackgroundContext().fetch(request)) ?? []
return movies.map { $0.name! } // error: unexpectedly found nil while unwrapping...

请注意,在上面的示例中,100% 确定 movies 中不存在 namenil 的实体。核心数据模型中的相应属性设置为非可选

当我更改代码如下所示(即不内联 newBackgroundContext())时,没有错误:

let context = container.newBackgroundContext()
let movies = (try? context.fetch(request)) ?? []
return movies.map { $0.name! } // no error this time

我对 Swift 还很陌生,并假设它与内存管理有关(例如 context 过早定义),但我希望能详细解释为什么第一个代码中会出现错误列表。

最佳答案

每当您在数组上运行映射函数时,它都会返回一个可选值。似乎名称没有任何值(value),并且您正在强制展开。尝试使用compactMap。

movies.compactMap { $0.name }

关于swift - 对实体数组执行 `map` 时获取 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58025461/

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