【问题标题】:Remove array index if instance object value and array value are the same如果实例对象值和数组值相同,则删除数组索引
【发布时间】:2018-12-26 17:36:09
【问题描述】:

我有一个名为 var geoLocList = [GeolocationModel]()

的数组

还有一个名为 var geoLocs = GeolocationModel()

的对象

geoLocs 的值附加到geoLocList

问题是,我正在尝试根据相同的 ID 将 geoLocList 中的索引替换为 geoLocs 的最新值。

我还是 iOS 应用开发的新手。 老实说,我不太了解下面的代码。我从浏览过的一些参考资料中得到它,并认为这会成功。但我错了。

这是代码

if let index = self.geoLocList.index(where: { $0.geoUid == geoLocs.geoUid }){
    self.geoLocList.remove(at: index)

【问题讨论】:

  • 您期望发生什么以及实际发生了什么?
  • @CleverError 我希望删除与新创建的 geoLocs 对象具有相同 id 的 geoLocList 索引。如果它们的 id 相同,则新的 geoLocs 将替换 geoLocList 索引。如果上面的代码满足条件,那么新的 geoLocs 将被附加到 geoLocList 数组中。但是上面的 if 条件不起作用
  • 代码没有问题,如果失败一定是因为geoUid之前没有正确设置。请发布完整的代码。

标签: arrays swift indexing closures


【解决方案1】:

这是一个使用问题中的if 子句的示例,它可能会帮助您找到代码中的错误。我使用 Xcode 游乐场编写了这个。

import Cocoa

struct Geo: CustomStringConvertible { //Simple struct used instead of GeolocationModel
    var id: Int //Identifier 
    var text: String

    var description: String {.  // added for better print() output
        return "\(id) - \(text)"
    }
}

var geoList = [Geo]()
var geo1 = Geo(id: 1, text: "First")
print("\(geo1) created")

if let index = geoList.index(where: { $0.id == geo1.id }){
    geoList.remove(at: index)
   print("geo removed")
}
geoList.append(geo1)
print("List contains: \(geoList)")

var geo2 = Geo(id: 1, text: "Second")
print("\(geo2) created")
if let index = geoList.index(where: { $0.id == geo2.id }){
    geoList.remove(at: index)
    print("geo removed")
}
geoList.append(geo2)
print("List contains: \(geoList)")

运行时的输出是

1 - 首次创建
列表包含:[1 - 第一个]
1 - 第二个创建。
地理删除
列表包含:[1 - Second]。

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 2021-06-07
    • 2022-06-10
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    相关资源
    最近更新 更多