我可以在 where 子句中使用 or ( || ) 吗?
Can I use an or ( || ) in a where clause?
我正在尝试扩展 Array
类型,但我只希望函数在类型为 Int
或 Float
时可用。
我知道我可以为一种类型做到这一点:
extension Sequence where Iterator.Element == Int { }
但是我可以为多种类型做吗?这就是我想要的:
extension Sequence where Iterator.Element == Int || Iterator.Element == Float { }
有可能实现吗?
这在概念上并没有真正起作用。在扩展中使用 where 允许您使用 Element 作为您指定的类型。如果你说它可以是多种类型,你可能根本没有 where 说明符。
如果您希望为多种类型添加特定功能,我建议您创建一个空协议并添加对所需类型的遵守。例如:
protocol WorksWithExtension { }
extension Int: WorksWithExtension { }
extension Float: WorksWithExtension { }
extension Sequence where Iterator.Element: WorksWithExtension {
//Do whatever you need to do here
}
我正在尝试扩展 Array
类型,但我只希望函数在类型为 Int
或 Float
时可用。
我知道我可以为一种类型做到这一点:
extension Sequence where Iterator.Element == Int { }
但是我可以为多种类型做吗?这就是我想要的:
extension Sequence where Iterator.Element == Int || Iterator.Element == Float { }
有可能实现吗?
这在概念上并没有真正起作用。在扩展中使用 where 允许您使用 Element 作为您指定的类型。如果你说它可以是多种类型,你可能根本没有 where 说明符。
如果您希望为多种类型添加特定功能,我建议您创建一个空协议并添加对所需类型的遵守。例如:
protocol WorksWithExtension { }
extension Int: WorksWithExtension { }
extension Float: WorksWithExtension { }
extension Sequence where Iterator.Element: WorksWithExtension {
//Do whatever you need to do here
}