@@ -34,53 +34,58 @@ class TestViewController: BaseViewController {
3434
3535 override func viewDidLoad( ) {
3636 super. viewDidLoad ( )
37- let jsonString = """
38- [
39- {
40- " enjoyCount " : 1 ,
41- " commentCount " : 1,
42- },
43- {
44- " enjoyCount " : 2,
45- " commentCount " : 2,
46- },
47- {
48- " enjoyCount " : 2,
49- " commentCount " : 2,
37+
38+ let dict : [ String : Any ] = [
39+ " size " : 1 ,
40+ " id " : 2 ,
41+ " name " : " Mccc "
42+ ]
43+
44+ guard let model = C . deserialize ( from : dict ) else { return }
45+
46+ print ( model . size )
47+ print ( model . id )
48+ print ( model . name )
49+ }
5050}
51- ]
51+
52+ class A : SmartCodable {
53+ var size : Int ?
54+ @IgnoredKey
55+ var attr : NSMutableAttributedString ?
56+ required init ( ) { }
57+ }
58+
59+ class B : A {
60+ var name : String ?
5261
53- """
54- guard let models = [ RecommendModel ] . deserialize ( from: jsonString) else {
55- return
56- }
57- print ( models)
58- print ( " \n " )
62+ enum CodingKeys : CodingKey {
63+ case name
64+ }
65+ required init ( from decoder: any Decoder ) throws {
66+ try super. init ( from: decoder)
5967
60- let uniqueRecommends = Array ( Set ( models ) )
61- print ( uniqueRecommends )
68+ let container = try decoder . container ( keyedBy : CodingKeys . self )
69+ self . name = try container . decodeIfPresent ( String . self , forKey : . name )
6270 }
63-
64- struct RecommendModel : SmartCodable , Equatable , Hashable {
71+ required init ( ) {
72+ super. init ( )
73+ }
74+ }
6575
66- /// 点赞数
67- var enjoyCount : Int = 0
68- /// 评论数
69- var commentCount : Int = 0
70-
71- @IgnoredKey
72- var priceText : NSAttributedString ? // 价格富文本
73-
74-
75- static func == ( lhs: RecommendModel , rhs: RecommendModel ) -> Bool {
76- return true
77- }
76+
77+ class C : B {
78+ var id : Int ?
79+ enum CodingKeys : CodingKey {
80+ case id
81+ }
82+ required init ( from decoder: any Decoder ) throws {
83+ try super. init ( from: decoder)
7884
79- // 手动实现 Hashable 协议
80- func hash ( into hasher : inout Hasher ) {
81- hasher . combine ( enjoyCount )
82- hasher . combine ( commentCount )
83- }
85+ let container = try decoder . container ( keyedBy : CodingKeys . self )
86+ self . id = try container . decodeIfPresent ( Int . self , forKey : . id )
87+ }
88+ required init ( ) {
89+ super . init ( )
8490 }
85-
8691}
0 commit comments