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

extension Array {
    
    func safeString(At index: Int) -> String {
        return safeObject(At: index, defaultValue: "")
    }
    
    func safeStringInt(At index: Int) -> String {
        return safeObject(At: index, defaultValue: "0")
    }
    
    func safeArray(At index: Int) -> [Any] {
        return safeObject(At: index, defaultValue: [])
    }
    
    func safeDictionary(At index: Int) -> [String: Any] {
        return safeObject(At: index, defaultValue: [:])
    }
    
    func safeNumber(At index: Int) -> NSNumber {
        return safeObject(At: index, defaultValue: NSNumber(value: 0))
    }
    
    func safeObject(At index: Int) -> Any {
        return safeObject(At: index, defaultValue: NSObject())
    }
    
    private func safeObject<T>(At index: Int, defaultValue: T) -> T {
        guard index >= 0 && index < count else { return defaultValue }
        let value = self[index]
        if value is NSNull { return defaultValue }
        return value as? T ?? defaultValue
    }
    
    func safeObj(At index: Int) -> Element? {
        if index >= 0,  index < count {
            return self[index]
        }
        return nil
    }
}
