Swift-过滤符合通用协议的对象

时间:2019-06-29 12:46:12

标签: ios swift generics protocols associated-types

我试图了解如何过滤符合通用协议的对象。
假设我已经进行了设置(可以完美编译):

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?
}

并假设我有一个带有多个子视图的UIView,其中一些子视图符合Restorable,而有些子视图不符合,而我只想获得符合Restorable的子视图,我通常会这样做:

let restorableSubviews = superview.subviews.compactMap({$0 as? (Restorable & UIView)})

但是出现以下编译错误:

Protocol 'Restorable' can only be used as a generic constraint because it has Self or associated type requirements

我在SOF中阅读了许多答案,但无法解决此问题。如何使编译器将我的通用协议视为一种类型,并仅获取相关的子视图?

0 个答案:

没有答案