I am currently writing a reusable UI component in Swift that's supposed to be consumed from both Obj-C/ Swift worlds (it's a mixed project). I defined a @objc
protocol without any associated types (since those are not allowed for @objc
protocols). In one of the methods in the component, I need to store the protocol as a type and need to find the index of a particular entry, somewhat similar to the following-
func select<T: Itemable>(_ item: T) {
guard let itemIndex = items.index(of: item) else {
return
}
//more stuf
}
where items
is an array of Itemable
(protocol) type.
However, I get the error saying I can not use it as a type conforming to Equatable since equatable has static requirements.
Itemable
is defined as following-
@objc protocol Itemable {
//methods and properties
}
Also, not sure how to make it conform to equatable. Apparently, the following helps but not sure why-
func ==<T: <Itemable>>(lhs: T, rhs: T) -> Bool {
return lhs.aProperty == rhs.aProperty
}
Seems to me like it might require type erasing, but not sure how to go about doing that.
Here's an abridged version of the protocol, showing all different types of methods and properties present- it does not really have anything static or associated type.
@objc protocol Itemable {
typealias voidBlock = () -> Void
var color: UIColor { get }
var screenParameters: [String : String] { get }
var screenView: String { get }
var iconImage: UIImage? { get }
@objc var accessibilityLabel: String? { get }
}
extension Array where Element: Itemable {
func index(of element: Element) -> Int? {
index(where: { $0.screenView == element.screenView })
}
}
guard
statement in question. Can you show the method/class it is in? – Sweeperitems
is[Itemable]
? In that case, I think one way (not sure if it's the only way) is to doas NSArray
and useindex(of:)
inNSArray
. – Sweeper