我可以在where子句中使用or或(||)吗? [英] Can I use an or ( || ) in a where clause?

查看:71
本文介绍了我可以在where子句中使用or或(||)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扩展 Array 类型,但是我只希望类型为 Int Float 的函数可用.

I am trying to extend the Array type, but I only want the functions available if the type is Int or Float.

我知道我可以针对一种类型执行此操作:

I know I can do this for one type:

extension Sequence where Iterator.Element == Int { }

但是我可以针对多种类型吗?这就是我想要的:

But can I do it for multiple types? This is sort of what I want:

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

有可能做到这一点吗?

推荐答案

从概念上讲,这实际上并不起作用.使用扩展名中的where可以将Element用作您指定的Type.如果您要说它可以是多种类型,那么您可能根本就没有where指示符.

This doesn't really work conceptually. Using the where in an extension allows you to use Element as the Type you're specifying. If you're saying it can be multiple Types, you might as well not have the where specifier at all.

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

If you're looking to add specific functionality for multiple types, I would recommend creating an empty protocol and add adherence to the desired Types. e.g:

protocol WorksWithExtension { }

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

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

这篇关于我可以在where子句中使用or或(||)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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