错误:参数类型为“日期?"不符合预期的类型"ReferenceConvertible" [英] Error: Argument type 'Date?' does not conform to expected type 'ReferenceConvertible'

查看:41
本文介绍了错误:参数类型为“日期?"不符合预期的类型"ReferenceConvertible"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Xcode中遇到错误:

I am getting an error in Xcode:

参数类型为日期?"与预期类型不符"ReferenceConvertible"

Argument type 'Date?' does not conform to expected type 'ReferenceConvertible'

此错误是什么意思?以及如何解决?

What does this error mean? And how to fix it?

示例:

我在核心数据中有一个实体,名称为ToDoItem(代码生成:类定义和模块:当前产品模块),并设置了2个属性:

I have an Entity in Core Data with a name ToDoItem (Codegen: Class Definition and Module: Current Product Module) and set 2 attributes:

  1. createdAt-非可选,默认值:当前日期
  2. 标题-非可选,默认值:空字符串

Xcode为我自动生成的类:

Xcode automatically generated class for me:

import Foundation
import CoreData


public class ToDoItem: NSManagedObject {

}

在ContentView中,我将以下代码传递给EditItemView到todoItem:

In ContentView I have this code where I am passing todoItem to EditItemView:

ForEach(toDoItems, id: \.self) {todoItem in

    NavigationLink(destination: EditItemView(todoItem: todoItem)) {

        ToDoItemView(title: todoItem.title ?? "", createdAt: todoItem.createdAt ?? Date())
}

在EditItemView中,我在此行得到错误:

And in EditItemView I am getting the error on this line:

Text("\(todoItem.createdAt, formatter: Self.dateFormat)")

如果使用,我可以使此错误消失:

I can make this error go away if I use:

Text("\(todoItem.createdAt!, formatter: Self.dateFormat)")

但是...即使在构建应用程序时也没有错误,在我使用应用程序中的删除"按钮删除todoItem之后,该应用程序崩溃在同一行,并显示以下错误:

But... even now there's no error while building app, after I delete a todoItem using Delete button in my app, the app crashes on the same exact line with error:

线程1:致命错误:展开包装时意外发现nil可选值

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我只是在学习,到目前为止,我知道这与某些值在Swift中是可选的有关,即使它们在Core Data中不是可选的.我读了用!展开可选值!大多数时候应该避免.但是,我仍然不知道如何解决此问题.如果todoItem.createdAt不起作用并且todoItem.createdAt如何使用todoItem.createdAt!使应用程序崩溃.

I am just learning and so far I know this is related to some values being optional in Swift even if they are not optional in Core Data. And I read that unwrapping optional values with ! should be avoided most of the times. But still, I don't know how to fix this problem. How to use todoItem.createdAt if todoItem.createdAt doesn't work and todoItem.createdAt! crashes the app.

推荐答案

无条件强制展开是一件坏事,实际上您现在知道为什么,总是尝试避免这种情况...

Force unwrap unconditionally is bad thing, actually you now know why, try to avoid it always...

这是该崩溃的可能修补程序之一:

Here is one of possible fixes for that crash:

Text(todoItem.createdAt != nil ? "\(todoItem.createdAt!, formatter: Self.dateFormat)" : "")

这篇关于错误:参数类型为“日期?"不符合预期的类型"ReferenceConvertible"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆