arrays - 具有通用项的 Swift 数组扩展

标签 arrays swift generics swift3

我正在使用 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/

相关文章:

c - 生成 1 和 0 并以菱形形式存储在数组内

C# 对象到 XML 字符串并返回

ruby - 在 Ruby 中将数组的数组组合成所有可能的组合,仅向前

c# - Box C# 对象作为通用接口(interface)

c# - 通用参数不可分配

arrays - 如何在不使用任何额外空间的情况下将矩阵旋转 90 度?

ios - 没有数据时不执行操作

ios - 如何获取 UTType 图像、音频和视频的所有扩展

ios - 我们能否创建一个源代码不会为其他人打开的自己的 pod 文件?

java - 将泛型转换为其子类