Caleb Kleveter Caleb Kleveter -4 years ago 108
Swift Question

Can I use an or ( || ) in a where clause?

I am trying to extend the

type, but I only want the functions available if the type is

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 { }

Is it possible to accomplish this?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download