gpt4 book ai didi

swift : affect struct by reference or "alias" to a variable

转载 作者:行者123 更新时间:2023-11-28 13:41:00 25 4
gpt4 key购买 nike

我必须更新一个结构,但是这个结构需要一个长表达式才能从我的 viewController 中找到:

let theMessage:Message? = self.messageSections.first(where: { $0.date == DateDMY(fromNSDate:msg.date) })?
.msgs.first(where: { $0 == msg })

我想改变这个结构的一个属性,而不是它的副本,我想更新它“它所在的位置”,即在 messageSections[].msgs[] 中

这里的问题是,如果我在上面的代码之后尝试这段代码:

theMessage.status = .NOT_SENT 

只会更新本地副本,不会更新messageSections[].msgs[]中的真实副本。所以当我重新加载我的 collectionView 时,没有任何变化。

我可以

self.messageSections.first(where: { $0.date == DateDMY(fromNSDate:msg.date) })?
.msgs.first(where: { $0 == msg }).status = .NOT_SENT

但是如果我必须在我的函数中多次操作这个属性,我不想每次都重写整个表达式。所以我正在寻找的是 C 中的东西:

let theMessage:Message?* = &self.messageSections.first(where: { $0.date == DateDMY(fromNSDate:msg.date) })?
.msgs.first(where: { $0 == msg })
if(theMessage != NULL)
theMessage->status = .NOT_SENT

我在其他问题中看到我可以在参数之前使用 & 并在参数名称之前使用 inout ,但它仅用于函数调用。我正在寻找一种在影响变量时为大表达式创建别名的方法,只是为了避免每次都重新编写它。

最佳答案

您可以使用firstIndex 获取数组中元素的索引,然后使用检索到的索引直接访问该元素。

if let messageSectionIndex = self.messageSections.first(where: { $0.date == DateDMY(fromNSDate:msg.date) }), let messageIndex = self.messageSections[messageSectionIndex].msgs.firstIndex(where: { $0 == msg }) {
self.messageSections[messageSectionIndex].msgs[messageIndex].status = .NOT_SENT
}

关于 swift : affect struct by reference or "alias" to a variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56029737/

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