BuiltInBridgeType.swift 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // BuiltInBridgeType.swift
  3. // HandyJSON
  4. //
  5. // Created by zhouzhuo on 15/07/2017.
  6. // Copyright © 2017 aliyun. All rights reserved.
  7. //
  8. import Foundation
  9. protocol _BuiltInBridgeType: _Transformable {
  10. static func _transform(from object: Any) -> _BuiltInBridgeType?
  11. func _plainValue() -> Any?
  12. }
  13. extension NSString: _BuiltInBridgeType {
  14. static func _transform(from object: Any) -> _BuiltInBridgeType? {
  15. if let str = String.transform(from: object) {
  16. return NSString(string: str)
  17. }
  18. return nil
  19. }
  20. func _plainValue() -> Any? {
  21. return self
  22. }
  23. }
  24. extension NSNumber: _BuiltInBridgeType {
  25. static func _transform(from object: Any) -> _BuiltInBridgeType? {
  26. switch object {
  27. case let num as NSNumber:
  28. return num
  29. case let str as NSString:
  30. let lowercase = str.lowercased
  31. if lowercase == "true" {
  32. return NSNumber(booleanLiteral: true)
  33. } else if lowercase == "false" {
  34. return NSNumber(booleanLiteral: false)
  35. } else {
  36. // normal number
  37. let formatter = NumberFormatter()
  38. formatter.numberStyle = .decimal
  39. return formatter.number(from: str as String)
  40. }
  41. default:
  42. return nil
  43. }
  44. }
  45. func _plainValue() -> Any? {
  46. return self
  47. }
  48. }
  49. extension NSArray: _BuiltInBridgeType {
  50. static func _transform(from object: Any) -> _BuiltInBridgeType? {
  51. return object as? NSArray
  52. }
  53. func _plainValue() -> Any? {
  54. return (self as? Array<Any>)?.plainValue()
  55. }
  56. }
  57. extension NSDictionary: _BuiltInBridgeType {
  58. static func _transform(from object: Any) -> _BuiltInBridgeType? {
  59. return object as? NSDictionary
  60. }
  61. func _plainValue() -> Any? {
  62. return (self as? Dictionary<String, Any>)?.plainValue()
  63. }
  64. }