Swift - Filter objects that conform to a generic protocol

若如初见. 提交于 2019-12-23 04:52:43

问题


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?

来源:https://stackoverflow.com/questions/56817656/swift-filter-objects-that-conform-to-a-generic-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!