Swift conform to protocol subclass

Viewed 933

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 Answers

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
}

Related