swift4.0 数据转模型

swift 4.0时代的到来,说明了swift已经趋于稳定了,已经完全可以入坑了.

下面就拿最简单的数据转模型来说说,实战一下.

接口使用:  http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1  

分别演示下:  1.SwiftyJSON 2.HandyJSON 3.ObjectMapper 4.swift4.0 Codable

说明:对上面几种方案使用过后1.SwiftyJSON直接对返回数据进行操作,不包含模型转换.个人不太喜欢

              2.HandyJSON阿里封装的数据转模型,朋友说这个轮子有点方

              3.ObjectMapper朋友推荐使用这个

              4.swift4.0 Codable,个人也不太喜欢

1.SwiftyJSON  

C层:

 1 //
 2 //  TabOneVC.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/19.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //  SwiftyJSON --  https://github.com/SwiftyJSON/SwiftyJSON
 8 
 9 import UIKit
10 import Alamofire
11 import SwiftyJSON
12 private let oneCellIdentifier = "oneCellIdentifier"
13 
14 class TabOneVC: UIViewController {
15 
16     lazy var oneTableView:UITableView = {
17         let tabView = UITableView.init(frame: UIScreen.main.bounds)
18         tabView.delegate = self
19         tabView.dataSource = self
20         tabView.rowHeight = 220.0
21         tabView.register(OneCell.self, forCellReuseIdentifier: oneCellIdentifier)
22         view.addSubview(tabView)
23         return tabView
24 
25     }()
26     
27     var ary:[JSON]! = []
28     
29     
30     override func viewDidLoad() {
31         super.viewDidLoad()
32         
33         Alamofire.request("http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1").responseJSON { (response) in
34             let data = response.result.value
35             let j = JSON.init(data!)
36             self.ary = j["lives"].array
37             self.oneTableView.reloadData()
38         }
39     }
40 
41     override func didReceiveMemoryWarning() {
42         super.didReceiveMemoryWarning()
43         // Dispose of any resources that can be recreated.
44     }
45 
46 
47 
48 }
49 extension TabOneVC: UITableViewDelegate,UITableViewDataSource{
50     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
51         return ary.count;
52     }
53     
54     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
55         let cell = tableView.dequeueReusableCell(withIdentifier: oneCellIdentifier, for: indexPath) as! OneCell
56         cell.jsonObj = ary[indexPath.row]
57         
58         return cell;
59         
60     }
61     
62     
63 }
SwiftyJSON

cell:

 1 //
 2 //  OneCell.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/19.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //
 8 
 9 import UIKit
10 import SwiftyJSON
11 import SDWebImage
12 class OneCell: UITableViewCell {
13     var jsonObj:JSON?{
14         didSet{
15             nameLabel.text =  String(describing: jsonObj!["creator"]["nick"]) + "-" + String(describing: jsonObj!["city"])
16             let str:String = String(describing: jsonObj!["creator"]["portrait"])
17             picImgView.sd_setImage(with: URL.init(string: str), completed: nil)            
18         }
19     }
20     
21     lazy var nameLabel:UILabel = {
22         let la = UILabel.init()
23         return la;
24     }()
25     
26     lazy var picImgView:UIImageView = {
27         let imgView = UIImageView.init()
28         return imgView;
29     }()
30     
31 
32     
33     override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
34         super.init(style: style, reuseIdentifier: reuseIdentifier)
35         setupUI()
36         addCons()
37     }
38     
39     
40     func setupUI(){
41         contentView.addSubview(nameLabel)
42         contentView.addSubview(picImgView)
43         
44     }
45     
46     func addCons(){
47         nameLabel.snp.makeConstraints { (make) in
48             make.leftMargin.equalTo(contentView.snp.left).offset(10)
49             make.rightMargin.equalTo(contentView.snp.right).offset(-10)
50             make.topMargin.equalTo(contentView.snp.top).offset(10)
51             make.height.equalTo(50)
52         }
53         picImgView.snp.makeConstraints { (make) in
54             make.leftMargin.equalTo(contentView.snp.left).offset(10)
55             make.topMargin.equalTo(nameLabel.snp.bottom).offset(20)
56             make.height.width.equalTo(120)
57         }
58         
59         
60     }
61     
62     required init?(coder aDecoder: NSCoder) {
63         fatalError("init(coder:) has not been implemented")
64     }
65 
66 }
SwiftyJSON

2.HandyJSON

C层:

 1 //
 2 //  TabTwoVC.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/19.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //  HandyJSON -- https://github.com/alibaba/HandyJSON
 8 
 9 import UIKit
10 import Alamofire
11 import HandyJSON
12 
13 private let twoCellIdentifier = "twoCellIdentifier"
14 class TabTwoVC: UIViewController {
15 
16     lazy var twoTableView:UITableView = {
17         let tabView = UITableView.init(frame: UIScreen.main.bounds)
18         tabView.delegate = self
19         tabView.dataSource = self
20         tabView.rowHeight = 220.0
21         tabView.register(TwoCell.self, forCellReuseIdentifier: twoCellIdentifier)
22         view.addSubview(tabView)
23 
24         return tabView
25     }()
26 
27     var ary:[Dictionary<String, Any>] = []
28     
29     override func viewDidLoad() {
30         super.viewDidLoad()
31         
32         Alamofire.request("http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1").responseJSON { (response) in
33             let data:Dictionary<String,Any> = response.result.value as! Dictionary
34             self.ary = data["lives"] as! [Dictionary<String, Any>]
35             self.twoTableView.reloadData()
36         }
37         
38     }
39     
40 
41     override func didReceiveMemoryWarning() {
42         super.didReceiveMemoryWarning()
43         // Dispose of any resources that can be recreated.
44     }
45     
46 
47 
48 }
49 
50 extension TabTwoVC: UITableViewDelegate,UITableViewDataSource{
51     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
52         return ary.count;
53     }
54     
55     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
56       let cell = tableView.dequeueReusableCell(withIdentifier: twoCellIdentifier, for: indexPath) as! TwoCell
57       cell.model = JSONDeserializer.deserializeFrom(dict: ary[indexPath.row])
58       return cell;
59         
60     }
61     
62     
63 }
HandyJSON

cell:

 1 //
 2 //  TwoCell.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/19.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //
 8 
 9 import UIKit
10 import SnapKit
11 import SDWebImage
12 class TwoCell: UITableViewCell {
13 
14     var model:TwoModel!{
15         didSet{
16             nameLabel.text = model.creator.nick + "-" + model.city
17             let str = model.creator.portrait
18             picImgView.sd_setImage(with: URL.init(string: str!), completed: nil)
19             
20         }
21     }
22     
23     lazy var nameLabel:UILabel = {
24        let la = UILabel.init()
25        return la;
26     }()
27     
28     lazy var picImgView:UIImageView = {
29         let imgView = UIImageView.init()
30         return imgView;
31     }()
32     
33     override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
34         super.init(style: style, reuseIdentifier: reuseIdentifier)
35         setupUI()
36         addCons()
37     }
38     
39     
40     func setupUI(){
41         contentView.addSubview(nameLabel)
42         contentView.addSubview(picImgView)
43         
44     }
45     
46     func addCons(){
47         nameLabel.snp.makeConstraints { (make) in
48             make.leftMargin.equalTo(contentView.snp.left).offset(10)
49             make.rightMargin.equalTo(contentView.snp.right).offset(-10)
50             make.topMargin.equalTo(contentView.snp.top).offset(10)
51             make.height.equalTo(50)
52         }
53         picImgView.snp.makeConstraints { (make) in
54             make.rightMargin.equalTo(contentView.snp.right).offset(-10)
55             make.topMargin.equalTo(nameLabel.snp.bottom).offset(20)
56             make.height.width.equalTo(120)
57         }
58         
59         
60     }
61     
62     required init?(coder aDecoder: NSCoder) {
63         fatalError("init(coder:) has not been implemented")
64     }
65 }
HandyJSON

model:

 1 //
 2 //  Model.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/19.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //
 8 
 9 import UIKit
10 import HandyJSON
11 struct  TwoModel: HandyJSON {
12     var city:String! 
13     var creator:TwoCreatorModel!
14 }
15 
16 struct TwoCreatorModel: HandyJSON {
17     var nick:String!
18     var portrait:String!
19 }
HandyJSON

3.ObjectMapper

C层:

 1 //
 2 //  TabThreeVC.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/20.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //  ObjectMapper --  https://github.com/Hearst-DD/ObjectMapper
 8 
 9 import UIKit
10 import Alamofire
11 import ObjectMapper
12 private let threeCellIdentifier = "threeCellIdentifier"
13 
14 class TabThreeVC: UIViewController {
15     
16     lazy var threeTableView:UITableView = {
17         let tabView = UITableView.init(frame: UIScreen.main.bounds)
18         tabView.delegate = self
19         tabView.dataSource = self
20         tabView.rowHeight = 220.0
21         tabView.register(ThreeCell.self, forCellReuseIdentifier: threeCellIdentifier)
22         return tabView
23     }()
24     var ary:[Dictionary<String, Any>] = []
25 
26     
27     
28     override func viewDidLoad() {
29         super.viewDidLoad()
30         view.addSubview(threeTableView)
31         Alamofire.request("http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1").responseJSON { (response) in
32             let data:Dictionary<String,Any> = response.result.value as! Dictionary
33             self.ary = data["lives"] as! [Dictionary<String, Any>]
34             self.threeTableView.reloadData()
35         }
36         
37     }
38 
39     override func didReceiveMemoryWarning() {
40         super.didReceiveMemoryWarning()
41         // Dispose of any resources that can be recreated.
42     }
43     
44 }
45 
46 
47 extension TabThreeVC: UITableViewDelegate,UITableViewDataSource{
48     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
49         return ary.count;
50     }
51     
52     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
53         let cell = tableView.dequeueReusableCell(withIdentifier: threeCellIdentifier, for: indexPath) as! ThreeCell
54         cell.model =  Mapper<ThreeModel>().map(JSON: ary[indexPath.row])
55         return cell;
56         
57     }
58     
59 
60     
61     
62 }
ObjectMapper

cell:

 1 //
 2 //  ThreeCell.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/20.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //
 8 
 9 import UIKit
10 import SnapKit
11 import SDWebImage
12 
13 class ThreeCell: UITableViewCell {
14 
15     var model:ThreeModel!{
16         didSet{
17             nameLabel.text = model.creator!.nick! + model.city!
18             let str = model.creator!.portrait
19             picImgView.sd_setImage(with: URL.init(string: str!), completed: nil)
20             
21         }
22     }
23     
24     
25     lazy var nameLabel:UILabel = {
26         let la = UILabel.init()
27         la.textAlignment = .center
28         return la;
29     }()
30     
31     lazy var picImgView:UIImageView = {
32         let imgView = UIImageView.init()
33         return imgView;
34     }()
35     
36     override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
37         super.init(style: style, reuseIdentifier: reuseIdentifier)
38         setupUI()
39         addCons()
40     }
41     
42     
43     func setupUI(){
44         contentView.addSubview(nameLabel)
45         contentView.addSubview(picImgView)
46         
47     }
48     
49     func addCons(){
50         nameLabel.snp.makeConstraints { (make) in
51             make.leftMargin.equalTo(contentView.snp.left).offset(10)
52             make.rightMargin.equalTo(contentView.snp.right).offset(-10)
53             make.topMargin.equalTo(contentView.snp.top).offset(10)
54             make.height.equalTo(50)
55         }
56         picImgView.snp.makeConstraints { (make) in
57             make.center.equalTo(contentView.snp.center)
58             make.height.width.equalTo(120)
59         }
60         
61     }
62     
63     required init?(coder aDecoder: NSCoder) {
64         fatalError("init(coder:) has not been implemented")
65     }
66 
67 }
ObjectMapper

model:

 1 //
 2 //  ThreeModel.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/20.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //
 8 
 9 import UIKit
10 import ObjectMapper
11 
12 struct ThreeModel: Mappable {
13     var city:String!
14     var creator:ThreeCreatorModel!
15     
16     mutating func mapping(map: Map) {
17         city <- map["city"]
18         creator <- map["creator"]
19     }
20     
21     init?(map: Map) {
22         
23     }
24     
25 }
26 
27 struct ThreeCreatorModel: Mappable {
28     var nick:String!
29     var portrait:String!
30     
31     mutating func mapping(map: Map) {
32         nick <- map["nick"]
33         portrait <- map["portrait"]
34     }
35     
36     init?(map: Map) {
37 
38     }
39     
40 }
ObjectMapper

4.swift4.0 Codable

C层:

 1 //
 2 //  TabFourVC.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/20.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //  自家孩子 swift4.0 Codable
 8 
 9 import UIKit
10 import Alamofire
11 
12 private let fourCellIdentifier = "fourCellIdentifier"
13 
14 class TabFourVC: UIViewController {
15 
16     lazy var fourTableView:UITableView = {
17         let tabView = UITableView.init(frame: UIScreen.main.bounds)
18         tabView.delegate = self
19         tabView.dataSource = self
20         tabView.rowHeight = 220.0
21         tabView.register(FourCell.self, forCellReuseIdentifier: fourCellIdentifier)
22         view.addSubview(tabView)
23         return tabView
24     }()
25     var model:FourModel!
26     
27     override func viewDidLoad() {
28         super.viewDidLoad()
29         Alamofire.request("http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1").responseData { (data) in
30             self.model = try! JSONDecoder().decode(FourModel.self, from: data.result.value!)
31             self.fourTableView.reloadData()
32         }
33     }
34 
35     override func didReceiveMemoryWarning() {
36         super.didReceiveMemoryWarning()
37         // Dispose of any resources that can be recreated.
38     }
39     
40 
41 }
42 
43 extension TabFourVC: UITableViewDelegate,UITableViewDataSource{
44     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
45         return model.lives.count;
46     }
47     
48     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
49         let cell = tableView.dequeueReusableCell(withIdentifier: fourCellIdentifier, for: indexPath) as! FourCell
50         cell.model = model.lives[indexPath.row]
51         return cell;
52     }
53     
54     
55 }
Codable

cell:

 1 //
 2 //  FourCell.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/20.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //
 8 
 9 import UIKit
10 import SnapKit
11 import SDWebImage
12 
13 class FourCell: UITableViewCell {
14     
15     var model:FourLivesModel!{
16         didSet{
17             nameLabel.text = model.city  + model.creator.nick
18             let str = model.creator.portrait
19             picImgView.sd_setImage(with: URL.init(string: str), completed: nil)
20         }
21     }
22     
23     lazy var nameLabel:UILabel = {
24         let la = UILabel.init()
25         la.textAlignment = .center
26         la.backgroundColor = UIColor.red
27         return la;
28     }()
29     
30     lazy var picImgView:UIImageView = {
31         let imgView = UIImageView.init()
32         return imgView;
33     }()
34     
35     override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
36         super.init(style: style, reuseIdentifier: reuseIdentifier)
37         setupUI()
38         addCons()
39     }
40     
41     
42     func setupUI(){
43         contentView.addSubview(nameLabel)
44         contentView.addSubview(picImgView)
45         
46     }
47     
48     func addCons(){
49         picImgView.snp.makeConstraints { (make) in
50             make.center.equalTo(contentView.snp.center)
51             make.height.width.equalTo(120)
52         }
53         nameLabel.snp.makeConstraints { (make) in
54             make.leftMargin.equalTo(contentView.snp.left).offset(10)
55             make.rightMargin.equalTo(contentView.snp.right).offset(-10)
56             make.topMargin.equalTo(picImgView.snp.bottom).offset(10)
57             make.height.equalTo(50)
58         }
59         
60     }
61     
62     required init?(coder aDecoder: NSCoder) {
63         fatalError("init(coder:) has not been implemented")
64     }
65 
66 }
Codable

model:

 1 //
 2 //  FourModel.swift
 3 //  myDemo
 4 //
 5 //  Created by Shaoting Zhou on 2017/12/20.
 6 //  Copyright © 2017年 Shaoting Zhou. All rights reserved.
 7 //
 8 
 9 import UIKit
10 
11 struct FourModel: Codable {
12     var error_msg:String
13     var lives:[FourLivesModel]
14     
15 }
16 
17 struct FourLivesModel: Codable {
18     var city:String
19     var creator:FourCreatorModel
20 }
21 
22 struct FourCreatorModel: Codable {
23     var nick:String
24     var portrait:String
25 }
Codable

基本的效果都长这样:

GitHub地址: https://github.com/pheromone/swift_study

 

原文地址:https://www.cnblogs.com/shaoting/p/8087153.html