arrays - 从 Swift 数组中删除自定义类型的集合

标签 arrays swift indexing indexof

我创建了一个 Swift 数组,其中包含自定义数据类型的两个实例的集合:

var myArray : [(MyDataType, MyDataType)]!

当我想向这个数组中添加项目时,使用以下代码很简单(其中 firstVarsecondVarMyDataType 的实例)

myArray.append((firstVar, secondVar))

我目前正在苦苦挣扎的是从 myArray 中删除项目.使用此代码,我得到一个错误 Value of type '[(MyDataType, MyDataType)]' has no member 'indexOf' :

    let indexOfA = myArray.indexOf((firstVar, secondVar))

    myArray.remove(at: indexOfA)

老实说有点困惑,所以关于如何获取 (MyDataType, MyDataType) 的项目索引的任何帮助这样我就可以将其从 myArray 中删除会非常有帮助!

最佳答案

您可以使您的 MyDataType 符合 Equatable 并使用 index(where:) 方法来查找您的元组(它也符合 Equatable):

Swift 4.1 利用 proposal se-0185

struct MyDataType: Equatable {
    let id: Int
}

var array : [(MyDataType,MyDataType)] = []

let tuple = (MyDataType(id: 1), MyDataType(id: 2))
array.append(tuple)

if let index = array.index(where: { $0 == tuple }) {
    array.remove(at: index)
}

关于arrays - 从 Swift 数组中删除自定义类型的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49867482/

相关文章:

mysql - 优化 MySQL 连接查询以删除 Using temporary 和 use an index?

jquery - 如何在 NodeJS 中更新 JSON 中的值并过滤以排除值?

PHP - 在多维数组中搜索

java - 在java中将数组插入/读取到sqlite数据库中

ios - 3D 触控 : registerForPreviewing in UICollectionViewCell

swift - 在 swift 的堆栈实现中包含方法

mysql - MySQL 可以为单个查询使用多个索引吗?

javascript - 根据另一个对象的 id 列出数组中的产品

ios - 为什么在 UITableViewController 中使用 NSCoding 会出错?

python - 如何从其他数组的不同起点对 2-D Numpy 数组的范围进行索引