0

I try to use generic method in order to find the index of the item in the array

public extension Array where Element: AnyObject {
    func findIdxOf<T: AnyObject>(_ item: T) -> Int? {
        return self.firstIndex{ $0 === item }
    }
}

Usage:

struct FeedData: Codable {
...
}

var currentFeedsArr: [FeedData] = []
var feed = FeedData()

let idx: Int? = currentFeedsArr.findIdxOf(feed) 

Error that I get -

Instance method 'findIdxOf' requires that 'FeedData' be a class type
Referencing instance method 'findIdxOf' on 'Array' requires that 'FeedData' be a class type

How to solve it?

Sirop4ik
  • 4,543
  • 2
  • 54
  • 121
  • You need to understand what means `AnyObject`, see https://stackoverflow.com/questions/25809168/anyobject-and-any-in-swift it's not for struct. That's why. Later, you might need to use `Equatable` to decides what means the use of `==` between to struct instances... – Larme Jan 17 '22 at 13:08
  • It's because of [AnyObject](https://developer.apple.com/documentation/swift/anyobject). – Desdenova Jan 17 '22 at 13:08
  • 1
    What you need is `extension Collection where Element: Equatable` and no need to make your method generic. Just make `item: Element`. Besides that not sure why would you recreate a method that is already present `firstIndex(of:)` no need to use a predicate `firstIndex(where:)` – Leo Dabus Jan 17 '22 at 13:35

1 Answers1

1

It's very simple. You said

where Element: AnyObject

That means: "Element must be a class." That is exactly what AnyObject means. (And your use of === implies that you know this, since only a class can be used with ===, the identity operator.)

So your findIdxOf applies only to an array whose element is a class. But FeedData is not a class. It is a struct.

So when you try to apply findIdxOf to an array of FeedData, the compiler complains.


Apart from that, it is unclear what your purpose was in creating this generic. If the goal was to use firstIndex(of:) with FeedData, then throw away your findIdxOf and simply declare FeedData as Equatable. If the goal was truly to implement a special version of firstIndex(of:) that compares class instances for identity, then declare FeedData as a class.

matt
  • 515,959
  • 87
  • 875
  • 1,141