2

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)
}
3
  • Might consider only keeping the String version. Array.map(_:) and Array.forEach(_:) let you convert every function that takes a single element into a function that can take an array of elements, without needing multiple overloads Commented Dec 8, 2020 at 22:42
  • @Alexander thanks for the recommendation. For my use case, I ended up creating two optional variables on the same func, one that accepts a String? and one that accepts a [String]? and rejecting if both are nil. It's a bit of an oddball use case for sure and would be safer if I just did the wrapper function recommendation like Rob suggested. Commented Dec 8, 2020 at 22:45
  • and rejecting if both are nil That's probably a misplaced responsibility. Unwrapping optionals should be done on the caller's side, not in the callee. Commented Dec 8, 2020 at 23:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the context, super helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.