12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- //
- // Dictionary+Ex.swift
- // TSLiveWallpaper
- //
- // Created by 100Years on 2024/12/20.
- //
- import Foundation
- public extension Dictionary where Key == String {
-
- func safeString(forKey key: String) -> String {
- return safeObject(forKey: key, defaultValue: "")
- }
-
- func safeStringInt(forKey key: String) -> String {
- return safeObject(forKey: key, defaultValue: "0")
- }
-
- func safeArray(forKey key: String) -> [Any] {
- return safeObject(forKey: key, defaultValue: [])
- }
-
- func safeDictionary(forKey key: String) -> [String: Any] {
- return safeObject(forKey: key, defaultValue: [:])
- }
-
- func safeNumber(forKey key: String) -> NSNumber {
- return safeObject(forKey: key, defaultValue: NSNumber(value: 0))
- }
-
- func safeInt(forKey key: String) -> Int {
- guard let value = self[key] , let valueInt = value as? Int else { return 0 }
- return valueInt
- }
-
- func safeObject(forKey key: String) -> Any {
- return safeObject(forKey: key, defaultValue: NSObject())
- }
-
- private func safeObject<T>(forKey key: String, defaultValue: T) -> T {
- guard let value = self[key] , let valueT = value as? T else { return defaultValue }
- return valueT
- }
- }
- public extension Dictionary where Key == String {
- /// 将字典转换为 JSON 字符串
- func toJSONString() -> String? {
- do {
- // 将字典转换为 JSON 数据
- let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
-
- // 将 JSON 数据转换为字符串
- return String(data: jsonData, encoding: .utf8)
- } catch {
- print("Error converting dictionary to JSON: \(error)")
- return nil
- }
- }
- }
|