在我的应用程序中,我有多个依赖模型的 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/