I'm trying to understand how to filter objects that conform to a generic protocol.
Let's assume I have this set up (which compiles perfectly):
public protocol StoryItem {
var id: Int64? { get }
}
public protocol Restorable: AnyObject {
associatedtype T : StoryItem
var storyItem: T? { get set }
}
public struct LabelItem: StoryItem {
public var id: Int64?
public var text: String?
}
public struct StickerItem: StoryItem {
public var id: Int64?
public var imageName: String?
}
class LabelView: UILabel, Restorable {
var storyItem: LabelItem?
}
class StickerView: UIImageView, Restorable {
var storyItem: StickerItem?
}
And assuming I have a UIView
with multiple subviews that some of them conform to Restorable
and some not, and I want to get only the subviews which conform to Restorable
, I'll usually do this:
let restorableSubviews = superview.subviews.compactMap({$0 as? (Restorable & UIView)})
But I'm getting the following compile error:
Protocol 'Restorable' can only be used as a generic constraint because it has Self or associated type requirements
I read many answers in SOF but couldn't work around this one. How do I make the compiler respect my generic-protocol as a type, and get only the relevant subviews?