我正在使用 Swift 3.1 并且有一些通用结构:
struct Section<InfoT: Equatable, ItemsT: Equatable> {
let info: InfoT?
let items: [ItemsT]
}
并希望使用自定义方法对这种泛型类型的元素进行数组扩展:
extension Array where Element == Section<Equatable, Equatable> {
// 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<Equatable, Equatable> {
^
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 <...>
等等...他们都不想编译。
最佳答案
试试这个:
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).")
}
}
}
}
关于arrays - 具有通用项的 Swift 数组扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43540206/