如何扩展协议 Optional,其中 Wrapped item 是 Array of Equatable 通用元素? [英] How to extend protocol Optional, where Wrapped item is Array of Equatable generic elements?

查看:64
本文介绍了如何扩展协议 Optional,其中 Wrapped item 是 Array of Equatable 通用元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会说这个问题是关于正确的扩展声明.

I would say this problem is about proper declaration of extension.

我想扩展充满通用元素的 Array,其中 Element 符合 Equatable.我设法做到了:

I would like to extend Array filled with generic Elements, where Element conforms to Equatable. I've managed to do that by :

    extension Array where Element: Equatable{
        // my code
    }

但是我想知道当填充了 Equatable 元素的数组在 Optional 中时如何正确声明扩展?我知道在这种情况下我实际上是在扩展协议 Optional,但我无法弄清楚其余的

However I'd like to know how to properly declare extension when the Array filled with Equatable elements is inside an Optional? I know that in this case I am actually extending protocol Optional, but I can't figure out the rest

我在想:

    extension Optional where Wrapped: Array  & Equatable {
      // my code
    }

想不通.有任何想法吗 ?

Can't figure it out. Any ideas ?

推荐答案

Cristik 提供了一个很好的解决方案.另一种方法是为一个可选的等价元素集合编写扩展:

Cristik provided a good solution. An alternative is to write an extension to an optional collection of equatable elements:

extension Optional where Wrapped: Collection, Wrapped.Element: Equatable {
    func foo() { }
}

这将适用于数组、数组切片和其他集合.

This would be applicable to arrays, array slices, and other collections.

根据扩展的作用,您可能希望使用 CollectionMutableCollectionBidirectionalCollectionRandomAccessCollection.

Depending on what the extension does, you may want to use a combination of Collection, MutableCollection, BidirectionalCollection, RandomAccessCollection.

这篇关于如何扩展协议 Optional,其中 Wrapped item 是 Array of Equatable 通用元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆