从Swift数组中移除自定义类型的集合 [英] Removing a collection of custom types from a Swift Array

查看:133
本文介绍了从Swift数组中移除自定义类型的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created a Swift array that contains collections of two instances of a custom data type:

var myArray : [(MyDataType, MyDataType)]!

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

When I want to add items to this array, it's trivial to do so with the following code (where firstVar and secondVar are instances of MyDataType)

myArray.append((firstVar, secondVar))

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

What I'm currently struggling with is removing items from myArray. Using this code, I get an error of Value of type '[(MyDataType, MyDataType)]' has no member 'indexOf':

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

    myArray.remove(at: indexOfA)

老实说有些困惑,所以任何有关如何获取(MyDataType, MyDataType)项索引的帮助都将非常有帮助!

Honestly somewhat confused, so any help as to how to get the index of an item of (MyDataType, MyDataType) so that I can then remove it from myArray would be extremely helpful!

推荐答案

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

You can make your MyDataType conform to Equatable and use index(where:) method to find your tuple (which conforms also to Equatable):

Swift 4.1 利用建议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)
}

这篇关于从Swift数组中移除自定义类型的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆