我有一个项目,我想在其中以某种方式通过 struct 进行记录.每个 struct 都应该有一个返回字符串的静态方法文档.我想为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有关,但我不知道该怎么做.