ios - Swift 符合协议(protocol)子类

标签 ios swift inheritance protocols subclass

在我的应用程序中,我有多个依赖模型的 UIView 子类。每个类都采用“Restorable”协议(protocol),该协议(protocol)包含模型的父类(super class)。每个子模型都描述了特定的 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?
}

有什么方法可以符合协议(protocol)子类吗?它将使 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
}

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

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
}

关于ios - Swift 符合协议(protocol)子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56814387/

相关文章:

swift - tvOS 中 UICollectionViewCell 的播放/暂停远程键

java - 更好的模式观察者?

java - 继承到子子类

ios - 如何从 MPMoviePlayerController 中播放的实际视频中获取坐标?

ios - NSMutableArray 与 NSDictionary 到 NSMutableDictionary

ios - 打开 safari 后终止应用程序 - swift

ios - 如何在数组中查找文档并删除它?

ios - 在 Swift 中更改类型

ios - Worklight 6.1 - App Center Installer 应用程序未在设备上显示 iOS 应用程序

typescript 在静态方法中获取类型