@@ -60,26 +60,22 @@ public extension AAObject {
6060 fileprivate func loopForMirrorChildren( _ mirrorChildren: Mirror . Children , _ representation: inout [ String : Any ] ) {
6161 for case let ( label? , value) in mirrorChildren {
6262 switch value {
63- case let value as AAObject : do {
63+ case let value as AAObject :
6464 representation [ label] = value. toDic ( )
65- }
6665
67- case let value as [ AAObject ] : do {
66+ case let value as [ AAObject ] :
67+ let valueCount = value. count
6868 var aaObjectArr = [ Any] ( )
69+ aaObjectArr. reserveCapacity ( valueCount)
6970
70- let valueCount = value. count
71- for i in 0 ..< valueCount {
72- let aaObject = value [ i]
73- let aaObjectDic = aaObject. toDic ( )
74- aaObjectArr. append ( aaObjectDic as Any )
71+ for aaObject in value {
72+ aaObjectArr. append ( aaObject. toDic ( ) )
7573 }
7674
7775 representation [ label] = aaObjectArr
78- }
7976
80- case let value as NSObject : do {
77+ case let value as NSObject :
8178 representation [ label] = value
82- }
8379
8480 default :
8581 // Ignore any unserializable properties
@@ -89,16 +85,21 @@ public extension AAObject {
8985 }
9086
9187 func toDic( ) -> [ String : Any ] {
92- var representation = [ String: Any] ( )
88+ // Create mirror once
89+ let mirror = Mirror ( reflecting: self )
90+
91+ // Estimate capacity based on property count
92+ let estimatedCapacity = mirror. children. underestimatedCount +
93+ ( mirror. superclassMirror? . children. underestimatedCount ?? 0 ) + 5
94+
95+ var representation = [ String: Any] ( minimumCapacity: estimatedCapacity)
9396
9497 // 遍历当前类的反射子属性
95- let mirrorChildren = Mirror ( reflecting: self ) . children
96- loopForMirrorChildren ( mirrorChildren, & representation)
98+ loopForMirrorChildren ( mirror. children, & representation)
9799
98100 // 遍历父类的反射子属性
99- let superMirrorChildren = Mirror ( reflecting: self ) . superclassMirror? . children
100- if superMirrorChildren? . count ?? 0 > 0 {
101- loopForMirrorChildren ( superMirrorChildren!, & representation)
101+ if let superMirror = mirror. superclassMirror, !superMirror. children. isEmpty {
102+ loopForMirrorChildren ( superMirror. children, & representation)
102103 }
103104
104105 // 如果实现了 SerializableWithComputedProperties 协议,获取计算属性
@@ -114,13 +115,11 @@ public extension AAObject {
114115
115116 func toJSON( ) -> String {
116117 do {
117- let data = try JSONSerialization . data ( withJSONObject: toDic ( ) as Any , options: [ ] )
118- guard let jsonStr = String ( data: data, encoding: String . Encoding. utf8) else { return " " }
119- return jsonStr
118+ let data = try JSONSerialization . data ( withJSONObject: toDic ( ) , options: [ . fragmentsAllowed] )
119+ return String ( data: data, encoding: . utf8) ?? " "
120120 } catch {
121+ print ( " JSON serialization error: \( error) " )
121122 return " "
122123 }
123124 }
124-
125- }
126-
125+ }
0 commit comments