//
//  Dictionary+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import Foundation

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
    }
}
