【问题标题】:Passing the properties of a struct to a class instance the elegant way以优雅的方式将结构的属性传递给类实例
【发布时间】:2021-02-24 21:34:44
【问题描述】:

我有一个这样的结构:

struct MyStruct: Codable {
  let id: String?
  let item: String?
  let description: String?
  let status: Bool?
}

在代码中的某个时刻,我必须将其存储在具有相同属性的核心数据实体上。所以我必须这样做:

// new core data item
let newItem = MyObject(context: context)
newItem.id = myStruct.id
newItem.item = myStruct.item
newItem.description = myStruct.description
newItem.status = myStruct.status

现在假设这两个项目都有 50 个属性。我必须有 50 条这样的线,将东西从一侧保存到另一侧。

有没有更漂亮的方法来做到这一点?

【问题讨论】:

  • 这就是我一直在做的事情......如果有更优雅的解决方案,我也很感兴趣。

标签: swift swift5


【解决方案1】:

您可以在返回 coreData 对象的结构中使用计算属性。例如:

struct MyStruct: Codable {
  let id: String?
  let item: String?
  let description: String?
  let status: Bool?

 func toCoreDataObject() -> MyObject {
     let newItem = MyObject(context: context)
     newItem.id = myStruct.id
     newItem.item = myStruct.item
     newItem.description = myStruct.description
     newItem.status = myStruct.status
     return newItem
   }

}

这样你在结构定义中写一次50个属性的列表,然后调用如下函数

let coreDataObject = myStruct.toCoreDataObject()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    相关资源
    最近更新 更多