Swift符合协议子类

时间:2019-06-29 00:58:22

标签: ios swift inheritance protocols subclass

在我的应用程序中,我有多个依赖于模型的UIView子类。每个采用“ Restorable”协议的类都拥有模型的超类。每个子模型都描述特定的UIView不常见属性。

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

我遇到以下编译器错误:

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

我唯一可以编译的方法是将ResizableLabel更改为

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

有什么方法可以符合协议子类?它将使Init流程更加整洁。谢谢您的帮助!

1 个答案:

答案 0 :(得分:2)

更改

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

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

现在可以编译代码。完整示例:

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
}