Swift 符合协议子类
Swift conform to protocol 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 进程更清洁。感谢您的帮助!
改变
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
}
在我的应用程序中,我有多个依赖模型的 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 进程更清洁。感谢您的帮助!
改变
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
}