Removing a collection of custom types from a Swift Array

那年仲夏 提交于 2020-01-25 08:23:07

问题


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

var myArray : [(MyDataType, MyDataType)]!

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))

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)

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!


回答1:


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 Taking advantage of 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)
}


来源:https://stackoverflow.com/questions/49867482/removing-a-collection-of-custom-types-from-a-swift-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!