ConditionalExpression.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2025 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. ///
  16. /// A `ConditionalExpression` is a `FunctionExpression` that evaluates to one of two expressions
  17. /// based on a boolean condition.
  18. ///
  19. /// This is equivalent to a ternary operator (`condition ? then : else`).
  20. ///
  21. /// Example of using `ConditionalExpression`:
  22. /// ```swift
  23. /// // Create a new field "status" based on the "rating" field.
  24. /// // If rating > 4.5, status is "top_rated", otherwise "regular".
  25. /// firestore.pipeline()
  26. /// .collection("products")
  27. /// .addFields([
  28. /// ConditionalExpression(
  29. /// Field("rating").greaterThan(4.5),
  30. /// then: Constant("top_rated"),
  31. /// else: Constant("regular")
  32. /// ).as("status")
  33. /// ])
  34. /// ```
  35. public class ConditionalExpression: FunctionExpression, @unchecked Sendable {
  36. /// Creates a new `ConditionalExpression`.
  37. ///
  38. /// - Parameters:
  39. /// - expression: The `BooleanExpression` to evaluate.
  40. /// - thenExpression: The `Expression` to evaluate if the boolean expression is `true`.
  41. /// - elseExpression: The `Expression` to evaluate if the boolean expression is `false`.
  42. public init(_ expr: BooleanExpression,
  43. then thenExpression: Expression,
  44. else elseExpression: Expression) {
  45. super.init("conditional", [expr, thenExpression, elseExpression])
  46. }
  47. }