0

I have this custom array:

var customArray = [CustomItem]()

Custom item is:

class CustomItem {
   let firstItem: Enumeration
   let data: Any

   // ... 
}

Enumeration contains an enumaration with different case. For example case example1, case example2 etc.

I add element with append with all the info like firstItem (enumeration etc).

What I need is to check if in my customArray I have a given item in my enumeration. Let's say I have to check if in customArray the enumeration .example1 exist (because I append it before) and in case delete it.

What is the safest and most elegant way to perform this?

Extra: what If i would like to add one element at the end of this custom arrray?

jamesCode
  • 1
  • 10
  • In your case: `if let index = customArray.firstIndex(where: { $0.firstItem == .example1 }) { customArray.remove(at: index) }` – vacawama Jul 09 '20 at 11:02

1 Answers1

-1

if you want find a specific item index you can use firstIndex(of: )

like this:

let index = customArray.firstIndex(of: CustomItem)
customArray.remove(at: index)

EDIT:

You have to make your object Equatable with an extension:

enter codextension CustomItem: Equatable {
static func ==(lhs: CustomItem, rhs: CustomItem) -> Bool {
    return lhs.firstItem == rhs.firstItem
} }

Now you can compare the objects with each other. this is my code from playground:

enum Enumeration {
    case opt1
    case op2
}

struct CustomItem {
    var firstItem: Enumeration
    let data: Any
}

extension CustomItem: Equatable {
    static func ==(lhs: CustomItem, rhs: CustomItem) -> Bool {
        return lhs.firstItem == rhs.firstItem
    }
}

class ViewController: UIViewController {
var customArray = [CustomItem]()
    
func searchAndDestory() {
    let index = customArray.firstIndex(of: CustomItem.init(firstItem: .op2, data: 0)) ?? 0
    customArray.remove(at: index)
    }
}
Jarret
  • 26
  • 5
  • But in my specific scenario how do I check the enumeration element in my customArray? – jamesCode Jul 09 '20 at 09:45
  • See my edit. I hope i understand your problem well and this is helpful. – Jarret Jul 09 '20 at 13:30
  • You have not improved your solution here in my opinion, now you are saying that 2 `CustomItem` objects are equal if their `firstItem` properties are equal even if other properties are different and I believe that is a false assumption. This could have very bad consequences if for example OP wants to add objects to a Set. – Joakim Danielson Jul 09 '20 at 15:27