Home > database >  Conditional Array Merge in Swift
Conditional Array Merge in Swift

Time:03-18

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!

CodePudding user response:

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

return primaryArray   (condition ? secondaryArray : [])

CodePudding user response:

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
  }
}
  • Related