[英]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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.