0

Using SwiftUI 3.0 and Swift 5.5 on Xcode 13.2, target development > iOS 15.0.0

I'm trying to merge two arrays if a condition is met, but only one if it isn't.

I have come up with this simple function:

func conditionalArrayMerge(primaryArray: [Item], secondaryArray: [Item], condition: Bool) -> [Item] {
        if condition {
            return primaryArray + secondaryArray
        } else {
            return primaryArray
        }
    }

Is this the most efficient way to do this?

I don't want to do it like this

return condition ? primaryArray + secondaryArray : primaryArray

I tried doing it like so:

return primaryArray + { condition ? secondaryArray : [] } as [Item]

But obviously, it didn't work (unless it's not obvious?)

What's the most efficient way to return an array with conditional merges?

Thank you!

2
  • 2
    "I don't want to do it like this" <- what's wrong with that way of doing it? Commented Mar 17, 2022 at 14:06
  • Because I want to see if there's an even shorter method to get the same result Commented Mar 17, 2022 at 14:10

2 Answers 2

3

Your syntax is wrong, you need parentheses around your ternary expression, not {}.

return primaryArray + (condition ? secondaryArray : [])
Sign up to request clarification or add additional context in comments.

Comments

1

What you're looking for is a variant of reduce that is missing from the standard library.

condition.reduce(primaryArray) { $0 + secondaryArray }
public extension Bool {
  /// Modify a value if `true`.
  /// - Returns: An unmodified value, when false.
  @inlinable func reduce<Result>(
    _ resultWhenFalse: Result,
    _ makeResult: (_ resultWhenFalse: Result) throws -> Result
  ) rethrows -> Result {
    self
      ? try makeResult(resultWhenFalse)
      : resultWhenFalse
  }
}

Comments

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.