我有一个项目,我想以某种方式通过结构来记录文档。每个结构都应该有一个返回String的静态方法文档。我想为Array
写一个扩展,这样我就可以在符合我的协议的对象数组上调用该函数,但它不起作用。
到目前为止,我得到了这个:
protocol Documentable {
static func document() -> String
}
extension Array: Documentable where Element == Documentable {
static func document() -> String {
guard let casted = Element.Type.self as? Documentable.Type else {
return "didn't work..."
}
return "[\(casted.document()), ...]"
}
}
struct StructA: Documentable {
static func document() -> String {
return "a"
}
}
// approach 1
// this leads to "didn't work..."
let a = Array<StructA>()
print(type(of: a).document())
// approach 2
// referencing static method 'document()' on 'Array' requires the types 'StructA' and 'any Documentable' be equivalent
let b = Array<StructA>.self
print(b.document())
字符串
方法1编译,但导致运行时错误,因为强制转换不知何故不工作,我觉得这没有什么意义,因为Element
必须符合我的协议,所以强制转换应该总是工作。
方法2不编译消息:
referencing static method 'document()' on 'Array' requires the types 'StructA' and 'any Documentable' be equivalent
型
这也很奇怪,因为StructA
确实符合我的协议。
这可能与this有关,但我不知道如何做到这一点。
1条答案
按热度按时间7uzetpgm1#
您的代码在
Array<Document>
的单个类型上添加扩展,而不是为所有符合Document
的T
添加Array<T>
。Element.document()
显然不能存在于Array<Document>
中。由于Element
与Document
相同,因此Element.document()
没有实现。参见the post you linked。你应该把
==
改成:
,这可能就是你想做的。字符串
现在你可以执行
Array<StructA>.document()
,它将返回"[a, ...]"
。