问题
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