2

Is there a way to type constrain a parameter to more than one constraint? Specifically, the object could be of the protocol Decodable or an Array with generic Decodable.

So like this:

func myFunc(obj:Decodable, Array<Decodable>)

I've tried approaching it like this, using a generic with multiple constraints, but it requires both to be protocals, which Array is not. Also, this is likely an AND constraint, not an OR as pointing out by MartinR:

func myFunc<T where T:Decodable, T:Array<Decodable>>(obj:T)

That fails because array is not a protocol. Is there a way to constrain a parameter to be one of two types, where one is not a protocol?

I'm trying to avoid a check that throws an error at runtime, which I could do, but seems like bad practice to me.

steventnorris
  • 5,656
  • 23
  • 93
  • 174
  • I've tried this before and never found a way to do it. Not to say it can't be done, but I wasn't able to find a way. – Mike Cole Sep 28 '16 at 18:09
  • You cannot constrain a parameter to `T1` *or* `T2`, neither for types nor for protocols. – Martin R Sep 28 '16 at 18:10
  • @MartinR You can for protocols using the above where, adjusting for clarity – steventnorris Sep 28 '16 at 18:10
  • Unless I am mistaken, that is a *and* composition, `T` must satisfy *both* constraints, compare http://stackoverflow.com/questions/24089145/multiple-type-constraints-in-swift. – Martin R Sep 28 '16 at 18:12
  • @MartinR Is it? Well that's unfortunate. I must have misread something. I'll double check my docs then. – steventnorris Sep 28 '16 at 18:13

1 Answers1

-1

You could use an if statement when your method is called. Then have two different versions of the method (one for each type of constraint) and depending on which constraint you need to use, call the appropriate method.

Steve
  • 1,121
  • 1
  • 12
  • 32