Dictionary+Ex.swift 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // Dictionary+Ex.swift
  3. // TSLiveWallpaper
  4. //
  5. // Created by 100Years on 2024/12/20.
  6. //
  7. import Foundation
  8. public extension Dictionary where Key == String {
  9. func safeString(forKey key: String) -> String {
  10. return safeObject(forKey: key, defaultValue: "")
  11. }
  12. func safeStringInt(forKey key: String) -> String {
  13. return safeObject(forKey: key, defaultValue: "0")
  14. }
  15. func safeArray(forKey key: String) -> [Any] {
  16. return safeObject(forKey: key, defaultValue: [])
  17. }
  18. func safeDictionary(forKey key: String) -> [String: Any] {
  19. return safeObject(forKey: key, defaultValue: [:])
  20. }
  21. func safeNumber(forKey key: String) -> NSNumber {
  22. return safeObject(forKey: key, defaultValue: NSNumber(value: 0))
  23. }
  24. func safeInt(forKey key: String) -> Int {
  25. guard let value = self[key] , let valueInt = value as? Int else { return 0 }
  26. return valueInt
  27. }
  28. func safeObject(forKey key: String) -> Any {
  29. return safeObject(forKey: key, defaultValue: NSObject())
  30. }
  31. private func safeObject<T>(forKey key: String, defaultValue: T) -> T {
  32. guard let value = self[key] , let valueT = value as? T else { return defaultValue }
  33. return valueT
  34. }
  35. }
  36. public extension Dictionary where Key == String {
  37. /// 将字典转换为 JSON 字符串
  38. func toJSONString() -> String? {
  39. do {
  40. // 将字典转换为 JSON 数据
  41. let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
  42. // 将 JSON 数据转换为字符串
  43. return String(data: jsonData, encoding: .utf8)
  44. } catch {
  45. print("Error converting dictionary to JSON: \(error)")
  46. return nil
  47. }
  48. }
  49. }