gpt4 book ai didi

arrays - 在 swift 中调用实例方法 'append' 时没有完全匹配

转载 作者:行者123 更新时间:2023-12-05 02:31:12 25 4
gpt4 key购买 nike

试图将两个模型合并或合并为一个模型第一个模型 = 项目 [ InboxModel]。 (我自己的收件箱)第二个模型 = items2 [MoInboxModel](SDK 收件箱)

第一 + 第二 -> 组合项

private var items: [InboxModel] = []
private var items2: [MoInboxModel] = []
private var combinedItems: [combinedInboxModel] = []

struct InboxModel {
let id: String
let title: String
let message: String
let date: Date
}

struct MoInboxModel {
let id: String
let title: String
let message: String
let date: Date
}

struct combinedInboxModel {
let id: String
let title: String
let message: String
let date: Date
}

self?.combinedItems.append(self?.items). //No exact matches in call to instance method 'append
self?.combinedItems.append(contentsOf: self?.items2 ?? []) //No exact matches in call to instance method 'append

为什么合并的时候会出错?如何正确合并?

最佳答案

您有三个不相关的类型 - InboxModelMoInboxModelcombinedInboxModel(应该是 CombinedInboxModel。即使它们都有同名的属性,它们是不同的类型。

接受InboxModelMoInboxModel 数组的combinedInboxModel 数组上没有append 函数。

您可以在两个输入数组中的每一个上使用 map 将它们转换为 CombinedInboxModel 数组,然后您可以将其放入 combinedItems .

大概您是在一个闭包中编写这段代码,这就是您有一个弱 self 的原因。最好先处理它,然后再处理您的数组。

guard let self = self else {
return
}

self.combinedItems = self.items.map { CombinedInboxModel(id:$0.id,title:$0.title,message:$0.message,date:$0.date) }

let items2 = self.items2.map { CombinedInboxModel(id:$0.id,title:$0.title,message:$0.message,date:$0.date) }

self.combinedItems.append(contentsOf:items2)

您还没有显示itemsitems2 来自哪里;是否可以只将它们作为同一结构的实例来获取?

关于arrays - 在 swift 中调用实例方法 'append' 时没有完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71645384/

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