gpt4 book ai didi

swift - WWDC2019 Session 204 - 使用可识别协议(protocol)的核心数据作为数据源

转载 作者:搜寻专家 更新时间:2023-10-31 19:40:10 24 4
gpt4 key购买 nike

在 WWDC19 第 204 次 session 上,展示了如何使用 Swift 5.1 和 List 函数构建 UI。我想使用 Core Data 而不是数据文件。问题是核心数据实体不符合Identifiable协议(protocol)。

我在网上广泛搜索并观看了几个核心数据视频,但它们都已过时。它们都没有涵盖 Swift 5.1 和新的 beta 函数(如 List)。

我创建了一个包含一些字段(名称、id -> 这是一个 UUID)的实体。然后我手动生成如下所示的源文件:

AccountsMO+CoreDataClass.swift:

import Foundation
import CoreData


public class AccountsMO: NSManagedObject
{

}

AccountsMO+CoreDataProperties.swift:

import Foundation
import CoreData


extension AccountsMO
{

@nonobjc public class func fetchRequest() -> NSFetchRequest<AccountsMO>
{
return NSFetchRequest<AccountsMO>(entityName: "Accounts")
}

@NSManaged public var balance: NSDecimalNumber?
@NSManaged public var id: UUID
@NSManaged public var name: String
@NSManaged public var type: Int16

}

这些可以工作,但我不能在 List 中使用它们,因为它们不符合 Identifiable 协议(protocol)。我假设有一些方法可以添加它,但我找不到它,无论是在核心数据实体中还是在此处。

我将我的数据加载到 ContentView 文件中并尝试在列表中使用它。根据我的尝试,我要么'无法推断复杂的闭包返回类型;添加显式类型以消除歧义',或者我得到'不符合可识别协议(protocol)'

最佳答案

来自 SwiftUI Tutorials

Lists work with identifiable data. You can make your data identifiable in one of two ways: by calling the identified(by:) method with a key path to a property that uniquely identifies each element, or by making your data type conform to the Identifiable protocol.

由于 AccountsMO 类型已经具有可识别协议(protocol)所需的 id 属性,只需声明符合可识别协议(protocol)即可。

import SwiftUI

extension AccountsMO: Identifiable {

}

关于swift - WWDC2019 Session 204 - 使用可识别协议(protocol)的核心数据作为数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689989/

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