How do I get a function to accept a String or an Array of Strings?

Viewed 52

I feel like this is a "generics" thing, but I can't figure out how others do it? I'm pretty sure in Typescript I just do String|String[] but not sure how it works in Swift. Here's my attempt:

func HiWorld(passedVar: String|[String]){
   print(passedVar)
}

or

func HiWorld<T, String|[String]>(passedVar: T){
   print(passedVar)
}
1 Answers

What you're describing is an overload. You just express it as two functions, where one chains to the more general version.

// Specialized version; a one-element list
func hiWorld(passedVar: String) {
   hiWorld(passedVar: [passedVar])
}

// general version; list of any length
func hiWorld(passedVar: [String]) {
   print(passedVar)
}

(In practice, this is often how you wind up implementing it in TypeScript as well, since you can't generally do the same things with all types. Your print example is very special and misleading case.)

The syntax you're describing is an algebraic data type, and Swift doesn't support that syntax directly. While it can be a convenient shortcut, Swift generally prefers using an explicit enum or a protocol in cases where this kind of overload wouldn't make sense.

Related