gpt4 book ai didi

ios - 来自 AnyObject 的 Swift 类型转换

转载 作者:行者123 更新时间:2023-11-28 09:19:14 24 4
gpt4 key购买 nike

我正在尝试从我的商店中获取数据,但出现以下错误:

“事件”与“AnyObject”不同

我有一个events 变量,它是一个Event 数组。我猜从获取请求返回的数据来自 AnyObject 类型。所以我尝试将其类型转换为 [Event] 但它不起作用,我也不知道为什么。

var events: [Event] = []

func loadDataFromDB() {
let fetchRequest = NSFetchRequest(entityName: "Event")
events = context?.executeFetchRequest(fetchRequest, error: nil) as [Event]
}

最佳答案

当涉及可选链时,这似乎是某种错误。使用这些替代方案来解决问题:

events = context?.executeFetchRequest(fetchRequest, error: nil) as [AnyObject]? as [Event]
events = (context?.executeFetchRequest(fetchRequest, error: nil))! as [Event]
events = context!.executeFetchRequest(fetchRequest, error: nil) as [Event]

为了安全起见,我建议使用:

if let result = context?.executeFetchRequest(fetchRequest, error: nil) {
events = result as [Event]
}

如果有错误,executeFetchRequest 返回 nil

关于ios - 来自 AnyObject 的 Swift 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156700/

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