Roi*_*lia 3 inheritance protocols subclass ios swift
在我的应用程序中,我有多个依赖于模型的 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?
}
Run Code Online (Sandbox Code Playgroud)
我收到以下编译器错误:
*Type 'ResizableLabel' does not conform to protocol 'Restorable'*
Run Code Online (Sandbox Code Playgroud)
我可以让它编译的唯一方法是更改ResizableLabel为
// Works
class ResizableLabel: UILabel, Restorable {
var storyItem: StoryItem?
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以符合协议子类吗?它将使 Init 进程更加干净。感谢您的帮助!
改变
public protocol Restorable: AnyObject {
var storyItem: StoryItem? { get set } // adopter must declare as StoryItem
}
Run Code Online (Sandbox Code Playgroud)
到
public protocol Restorable: AnyObject {
associatedtype T : StoryItem
var storyItem: T? { get set } // adopter must declare as StoryItem adopter
}
Run Code Online (Sandbox Code Playgroud)
现在你的代码可以编译了。完整示例:
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
}
Run Code Online (Sandbox Code Playgroud)