Swift conform to protocol subclass

﹥>﹥吖頭↗ 提交于 2019-12-31 03:45:07

问题


Within my app, I have multiple UIView subclasses that depend on a model. Each of the classes adopting 'Restorable' protocol which holds the superclass of the model. Each sub-model describes the specific UIView not-common properties.

// Super-model
public protocol StoryItem {
    var id: Int64? { get }
}

// Parent protocol
public protocol Restorable: AnyObject {
    var storyItem: StoryItem? { get set }
}

// Specific protocol
public struct TextItem: StoryItem {
    public var id: Int64?
    public var text: String?
}

// Not complling
class ResizableLabel: UILabel, Restorable {
    var storyItem: TextItem?
}

I'm getting the following compiler error:

*Type 'ResizableLabel' does not conform to protocol 'Restorable'*

The only way I can make it compile is by changing ResizableLabel to

// Works
class ResizableLabel: UILabel, Restorable {
    var storyItem: StoryItem?
}

Is there any way to conform to protocol subclass? it'll make the Init process much cleaner. Thank you for your help!


回答1:


Change

public protocol Restorable: AnyObject {
    var storyItem: StoryItem? { get set } // adopter must declare as StoryItem
}

to

public protocol Restorable: AnyObject {
    associatedtype T : StoryItem
    var storyItem: T? { get set } // adopter must declare as StoryItem adopter
}

Now your code compiles. Full example:

public protocol StoryItem {
    var id: Int64? { get }
}
public protocol Restorable: AnyObject {
    associatedtype T : StoryItem
    var storyItem: T? { get set }
}
public struct TextItem: StoryItem {
    public var id: Int64?
    public var text: String?
}
class ResizableLabel: UILabel, Restorable {
    var storyItem: TextItem? // ok because TextItem is a StoryItem adopter
}



来源:https://stackoverflow.com/questions/56814387/swift-conform-to-protocol-subclass

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