加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 我可以在where子句中使用or(||)吗?

发布时间:2020-12-14 04:43:02 所属栏目:百科 来源:网络整理
导读:我正在尝试扩展Array类型,但我只希望函数可用,如果类型是Int或Float. 我知道我可以为一种类型做到这一点: extension Sequence where Iterator.Element == Int { } 但我能为多种类型做到吗?这就是我想要的东西: extension Sequence where Iterator.Element
我正在尝试扩展Array类型,但我只希望函数可用,如果类型是Int或Float.

我知道我可以为一种类型做到这一点:

extension Sequence where Iterator.Element == Int { }

但我能为多种类型做到吗?这就是我想要的东西:

extension Sequence where Iterator.Element == Int || Iterator.Element == Float { }

有可能做到这一点吗?

解决方法

这在概念上并没有真正起作用.使用扩展中的where允许您使用Element作为您指定的Type.如果你说它可以是多个类型,你可能根本就没有where说明符.

如果您要为多种类型添加特定功能,我建议您创建一个空协议并添加对所需类型的依从性.例如:

protocol WorksWithExtension { }

extension Int: WorksWithExtension { }
extension Float: WorksWithExtension { }

extension Sequence where Iterator.Element: WorksWithExtension {
    //Do whatever you need to do here
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读