Swift符合协议子类 [英] Swift conform to protocol subclass

查看:76
本文介绍了Swift符合协议子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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'*

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

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

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

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

推荐答案

更改

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
}

现在您的代码可以编译了.完整示例:

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
}

这篇关于Swift符合协议子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆