PartsRepresentable.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2023 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. /// A protocol describing any data that could be serialized to model-interpretable input data,
  16. /// where the serialization process might fail with an error.
  17. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, *)
  18. public protocol ThrowingPartsRepresentable {
  19. func tryPartsValue() throws -> [ModelContent.Part]
  20. }
  21. /// A protocol describing any data that could be serialized to model-interpretable input data,
  22. /// where the serialization process cannot fail with an error. For a failable conversion, see
  23. /// ``ThrowingPartsRepresentable``
  24. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, *)
  25. public protocol PartsRepresentable: ThrowingPartsRepresentable {
  26. var partsValue: [ModelContent.Part] { get }
  27. }
  28. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, *)
  29. public extension PartsRepresentable {
  30. func tryPartsValue() throws -> [ModelContent.Part] {
  31. return partsValue
  32. }
  33. }
  34. /// Enables a ``ModelContent.Part`` to be passed in as ``ThrowingPartsRepresentable``.
  35. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, *)
  36. extension ModelContent.Part: ThrowingPartsRepresentable {
  37. public typealias ErrorType = Never
  38. public func tryPartsValue() throws -> [ModelContent.Part] {
  39. return [self]
  40. }
  41. }
  42. /// Enable an `Array` of ``ThrowingPartsRepresentable`` values to be passed in as a single
  43. /// ``ThrowingPartsRepresentable``.
  44. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, *)
  45. extension [ThrowingPartsRepresentable]: ThrowingPartsRepresentable {
  46. public func tryPartsValue() throws -> [ModelContent.Part] {
  47. return try compactMap { element in
  48. try element.tryPartsValue()
  49. }
  50. .flatMap { $0 }
  51. }
  52. }
  53. /// Enables a `String` to be passed in as ``ThrowingPartsRepresentable``.
  54. @available(iOS 15.0, macOS 11.0, macCatalyst 15.0, tvOS 15.0, *)
  55. extension String: PartsRepresentable {
  56. public var partsValue: [ModelContent.Part] {
  57. return [.text(self)]
  58. }
  59. }