Removing a collection of custom types from a Swift Array
Asked Answered
M

1

0

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!

Millur answered 16/4, 2018 at 23:4 Comment(0)
W
2

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)
}
Whaler answered 16/4, 2018 at 23:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.