BuiltInBasicType.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /*
  2. * Copyright 1999-2101 Alibaba Group.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. // Created by zhouzhuo on 7/7/16.
  17. //
  18. import Foundation
  19. protocol _BuiltInBasicType: _Transformable {
  20. static func _transform(from object: Any) -> Self?
  21. func _plainValue() -> Any?
  22. }
  23. // Suppport integer type
  24. protocol IntegerPropertyProtocol: FixedWidthInteger, _BuiltInBasicType {
  25. init?(_ text: String, radix: Int)
  26. init(_ number: NSNumber)
  27. }
  28. extension IntegerPropertyProtocol {
  29. static func _transform(from object: Any) -> Self? {
  30. switch object {
  31. case let str as String:
  32. return Self(str, radix: 10)
  33. case let num as NSNumber:
  34. return Self(num)
  35. default:
  36. return nil
  37. }
  38. }
  39. func _plainValue() -> Any? {
  40. return self
  41. }
  42. }
  43. extension Int: IntegerPropertyProtocol {}
  44. extension UInt: IntegerPropertyProtocol {}
  45. extension Int8: IntegerPropertyProtocol {}
  46. extension Int16: IntegerPropertyProtocol {}
  47. extension Int32: IntegerPropertyProtocol {}
  48. extension Int64: IntegerPropertyProtocol {}
  49. extension UInt8: IntegerPropertyProtocol {}
  50. extension UInt16: IntegerPropertyProtocol {}
  51. extension UInt32: IntegerPropertyProtocol {}
  52. extension UInt64: IntegerPropertyProtocol {}
  53. extension Bool: _BuiltInBasicType {
  54. static func _transform(from object: Any) -> Bool? {
  55. switch object {
  56. case let str as NSString:
  57. let lowerCase = str.lowercased
  58. if ["0", "false"].contains(lowerCase) {
  59. return false
  60. }
  61. if ["1", "true"].contains(lowerCase) {
  62. return true
  63. }
  64. return nil
  65. case let num as NSNumber:
  66. return num.boolValue
  67. default:
  68. return nil
  69. }
  70. }
  71. func _plainValue() -> Any? {
  72. return self
  73. }
  74. }
  75. // Support float type
  76. protocol FloatPropertyProtocol: _BuiltInBasicType, LosslessStringConvertible {
  77. init(_ number: NSNumber)
  78. }
  79. extension FloatPropertyProtocol {
  80. static func _transform(from object: Any) -> Self? {
  81. switch object {
  82. case let str as String:
  83. return Self(str)
  84. case let num as NSNumber:
  85. return Self(num)
  86. default:
  87. return nil
  88. }
  89. }
  90. func _plainValue() -> Any? {
  91. return self
  92. }
  93. }
  94. extension Float: FloatPropertyProtocol {}
  95. extension Double: FloatPropertyProtocol {}
  96. fileprivate let formatter: NumberFormatter = {
  97. let formatter = NumberFormatter()
  98. formatter.usesGroupingSeparator = false
  99. formatter.numberStyle = .decimal
  100. formatter.maximumFractionDigits = 16
  101. return formatter
  102. }()
  103. extension String: _BuiltInBasicType {
  104. static func _transform(from object: Any) -> String? {
  105. switch object {
  106. case let str as String:
  107. return str
  108. case let num as NSNumber:
  109. // Boolean Type Inside
  110. if NSStringFromClass(type(of: num)) == "__NSCFBoolean" {
  111. if num.boolValue {
  112. return "true"
  113. } else {
  114. return "false"
  115. }
  116. }
  117. return formatter.string(from: num)
  118. case _ as NSNull:
  119. return nil
  120. default:
  121. return "\(object)"
  122. }
  123. }
  124. func _plainValue() -> Any? {
  125. return self
  126. }
  127. }
  128. // MARK: Optional Support
  129. extension Optional: _BuiltInBasicType {
  130. static func _transform(from object: Any) -> Optional? {
  131. if let value = (Wrapped.self as? _Transformable.Type)?.transform(from: object) as? Wrapped {
  132. return Optional(value)
  133. } else if let value = object as? Wrapped {
  134. return Optional(value)
  135. }
  136. return nil
  137. }
  138. func _getWrappedValue() -> Any? {
  139. return self.map( { (wrapped) -> Any in
  140. return wrapped as Any
  141. })
  142. }
  143. func _plainValue() -> Any? {
  144. if let value = _getWrappedValue() {
  145. if let transformable = value as? _Transformable {
  146. return transformable.plainValue()
  147. } else {
  148. return value
  149. }
  150. }
  151. return nil
  152. }
  153. }
  154. // MARK: Collection Support : Array & Set
  155. extension Collection {
  156. static func _collectionTransform(from object: Any) -> [Iterator.Element]? {
  157. guard let arr = object as? [Any] else {
  158. InternalLogger.logDebug("Expect object to be an array but it's not")
  159. return nil
  160. }
  161. typealias Element = Iterator.Element
  162. var result: [Element] = [Element]()
  163. arr.forEach { (each) in
  164. if let element = (Element.self as? _Transformable.Type)?.transform(from: each) as? Element {
  165. result.append(element)
  166. } else if let element = each as? Element {
  167. result.append(element)
  168. }
  169. }
  170. return result
  171. }
  172. func _collectionPlainValue() -> Any? {
  173. typealias Element = Iterator.Element
  174. var result: [Any] = [Any]()
  175. self.forEach { (each) in
  176. if let transformable = each as? _Transformable, let transValue = transformable.plainValue() {
  177. result.append(transValue)
  178. } else {
  179. InternalLogger.logError("value: \(each) isn't transformable type!")
  180. }
  181. }
  182. return result
  183. }
  184. }
  185. extension Array: _BuiltInBasicType {
  186. static func _transform(from object: Any) -> [Element]? {
  187. return self._collectionTransform(from: object)
  188. }
  189. func _plainValue() -> Any? {
  190. return self._collectionPlainValue()
  191. }
  192. }
  193. extension Set: _BuiltInBasicType {
  194. static func _transform(from object: Any) -> Set<Element>? {
  195. if let arr = self._collectionTransform(from: object) {
  196. return Set(arr)
  197. }
  198. return nil
  199. }
  200. func _plainValue() -> Any? {
  201. return self._collectionPlainValue()
  202. }
  203. }
  204. // MARK: Dictionary Support
  205. extension Dictionary: _BuiltInBasicType {
  206. static func _transform(from object: Any) -> [Key: Value]? {
  207. guard let dict = object as? [String: Any] else {
  208. InternalLogger.logDebug("Expect object to be an NSDictionary but it's not")
  209. return nil
  210. }
  211. var result = [Key: Value]()
  212. for (key, value) in dict {
  213. if let sKey = key as? Key {
  214. if let nValue = (Value.self as? _Transformable.Type)?.transform(from: value) as? Value {
  215. result[sKey] = nValue
  216. } else if let nValue = value as? Value {
  217. result[sKey] = nValue
  218. }
  219. }
  220. }
  221. return result
  222. }
  223. func _plainValue() -> Any? {
  224. var result = [String: Any]()
  225. for (key, value) in self {
  226. if let key = key as? String {
  227. if let transformable = value as? _Transformable {
  228. if let transValue = transformable.plainValue() {
  229. result[key] = transValue
  230. }
  231. }
  232. }
  233. }
  234. return result
  235. }
  236. }