Referencing instance method 'findIdxOf' on 'Array' requires that 'FeedData' be a class type
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?
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.