作者:黄秋蝉_961 | 来源:互联网 | 2023-02-06 06:00
我正在使用Swift 3.1并有一些通用的结构:
struct Section {
let info: InfoT?
let items: [ItemsT]
}
并希望使用自定义方法对此泛型类型的元素进行数组扩展:
extension Array where Element == Section {
// Just dummy example function:
func debugDummy() {
for section in self {
let info = section.info
print("section info: \(info).")
for item in section.items {
print("item: \(item).")
}
}
}
}
这给了我编译错误:
error: using 'Equatable' as a concrete type conforming to protocol 'Equatable' is not supported
extension Array where Element == Section {
^
error: GenericsListPlayground.playground:6:24: error: value of type 'Element' has no member 'info'
let info = section.info
^~~~~~~ ~~~~
error: GenericsListPlayground.playground:8:25: error: value of type 'Element' has no member 'items'
for item in section.items {
^~~~~~~ ~~~~~
如何正确申报此类延期?我已尝试过几种变体来声明此扩展名,例如:
extension Array where Element == Section (no arguments)
生产:
error: reference to generic type 'Section' requires arguments in <...>
等...他们都不想编译.
1> Eppilo..:
试试这个:
import Foundation
protocol Section {
associatedtype InfoT: Equatable
associatedtype ItemsT: Equatable
var info: InfoT? { get }
var items: [ItemsT] { get }
}
extension Array where Element: Section {
// Just dummy example function:
func debugDummy() {
for section in self {
let info = section.info
print("section info: \(String(describing: info)).")
for item in section.items {
print("item: \(item).")
}
}
}
}