Array+Ex.swift 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //
  2. // Array+Ex.swift
  3. // TSLiveWallpaper
  4. //
  5. // Created by 100Years on 2024/12/20.
  6. //
  7. public extension Array {
  8. func safeString(At index: Int) -> String {
  9. return safeObject(At: index, defaultValue: "")
  10. }
  11. func safeStringInt(At index: Int) -> String {
  12. return safeObject(At: index, defaultValue: "0")
  13. }
  14. func safeArray(At index: Int) -> [Any] {
  15. return safeObject(At: index, defaultValue: [])
  16. }
  17. func safeDictionary(At index: Int) -> [String: Any] {
  18. return safeObject(At: index, defaultValue: [:])
  19. }
  20. func safeNumber(At index: Int) -> NSNumber {
  21. return safeObject(At: index, defaultValue: NSNumber(value: 0))
  22. }
  23. func safeObject(At index: Int) -> Any {
  24. return safeObject(At: index, defaultValue: NSObject())
  25. }
  26. private func safeObject<T>(At index: Int, defaultValue: T) -> T {
  27. guard index >= 0 && index < count else { return defaultValue }
  28. let value = self[index]
  29. if value is NSNull { return defaultValue }
  30. return value as? T ?? defaultValue
  31. }
  32. func safeObj(At index: Int) -> Element? {
  33. if index >= 0, index < count {
  34. return self[index]
  35. }
  36. return nil
  37. }
  38. }