1
0

Foundation.swift 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // This source file is part of the Swift Argument Parser open source project
  4. //
  5. // Copyright (c) 2025 Apple Inc. and the Swift project authors
  6. // Licensed under Apache License v2.0 with Runtime Library Exception
  7. //
  8. // See https://swift.org/LICENSE.txt for license information
  9. //
  10. //===----------------------------------------------------------------------===//
  11. #if compiler(>=6.0)
  12. #if canImport(FoundationEssentials)
  13. import FoundationEssentials
  14. #else
  15. import Foundation
  16. #endif
  17. #else
  18. #if canImport(FoundationEssentials)
  19. import FoundationEssentials
  20. #else
  21. import Foundation
  22. #endif
  23. #endif
  24. extension Error {
  25. func describe() -> String {
  26. if let description = (self as? LocalizedError)?.errorDescription {
  27. return description
  28. } else {
  29. #if canImport(FoundationEssentials)
  30. return String(describing: self)
  31. #else
  32. if Swift.type(of: self) is NSError.Type {
  33. return self.localizedDescription
  34. } else {
  35. return String(describing: self)
  36. }
  37. #endif
  38. }
  39. }
  40. }
  41. enum ArgParserJSONEncoder {
  42. static func encode<T: Encodable>(_ value: T) -> String {
  43. #if canImport(FoundationEssentials)
  44. let encoder = FoundationEssentials.JSONEncoder()
  45. #else
  46. let encoder = Foundation.JSONEncoder()
  47. #endif
  48. encoder.outputFormatting = .prettyPrinted
  49. encoder.outputFormatting.insert(.sortedKeys)
  50. guard let encoded = try? encoder.encode(value) else { return "" }
  51. return String(data: encoded, encoding: .utf8) ?? ""
  52. }
  53. }