Swift:通过引用或对变量的“别名”来影响结构

时间:2019-05-07 20:03:12

标签: swift struct reference

我必须更新一个结构,但是此结构需要从我的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,但仅用于函数调用。我正在寻找一种在影响变量时为大型表达式创建别名的方法,以避免每次都重新写入它。

1 个答案:

答案 0 :(得分:1)

您可以使用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
}