【发布时间】:2018-07-07 11:15:55
【问题描述】:
我有这个功能:
public protocol ContentType {
associatedtype T
static var allTypes: [T] { get }
static func getContentType(contentTypeId: String) -> T
var contentTypeId: String? { get }
}
public protocol Copyable: class {
associatedtype T
static func copy(old: T, new: T)
}
public protocol CopyableContentType: class {
associatedtype T
init(existingContentType: T, newContentTypeId: String?)
}
我想为一个类提供一个默认初始化器:
- 符合
ContentType - 符合
Copyable
使用上面的代码,我总是在所需的 init 中做同样的事情:调用实现类的复制函数。有没有办法在保留这个初始化程序的同时省略跨类的重复代码?我想把它添加到协议扩展中:
public extension CopyableContentType where Self: ContentType & Copyable {
typealias T = Self // So wrong but I have no idea what to put here
// T should be the same T as the T usud in ContentType and Copyable
init(existingContentType: T, newContentTypeId: String?) {
Self.copy(old: existingContentType, new: self)
}
}
但这会导致一些错误。我不知道在 typealias 中输入什么,我不能使用相关类型。有什么方法可以提供调用复制函数的默认初始化程序?
【问题讨论】:
-
A CopyableContentType 应该是 Copyable 和 ContentType,因此可能从它们派生 CopyableContentType。然而,很难理解您希望 API 的使用方式。你能写一个例子来准确地展示你将如何使用新的 API 吗?
extension CopyableContentType where Self: ContentType & Copyable仅表示如果 Self 实现了这两个协议,那么我为您提供了我的“酷”扩展功能,您可以使用它。否则,您必须自己实现该功能。而且 where 并没有说所有的 associatedTypes 必须是相同的类型。 -
您可以使用扩展中的 where 子句将 CopyableContentType 的 T 限制为 ContentType.T 和 Copyable.T。
标签: swift protocols type-alias associated-types