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层:
- //
- // TabOneVC.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/19.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- // SwiftyJSON -- https://github.com/SwiftyJSON/SwiftyJSON
- import UIKit
- import Alamofire
- import SwiftyJSON
- private let oneCellIdentifier = "oneCellIdentifier"
- class TabOneVC: UIViewController {
- lazy var oneTableView:UITableView = {
- let tabView = UITableView.init(frame: UIScreen.main.bounds)
- tabView.delegate = self
- tabView.dataSource = self
- tabView.rowHeight = 220.0
- tabView.register(OneCell.self, forCellReuseIdentifier: oneCellIdentifier)
- view.addSubview(tabView)
- return tabView
- }()
- var ary:[JSON]! = []
- override func viewDidLoad() {
- super.viewDidLoad()
- Alamofire.request("http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1").responseJSON { (response) in
- let data = response.result.value
- let j = JSON.init(data!)
- self.ary = j["lives"].array
- self.oneTableView.reloadData()
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
- extension TabOneVC: UITableViewDelegate,UITableViewDataSource{
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return ary.count;
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: oneCellIdentifier, for: indexPath) as! OneCell
- cell.jsonObj = ary[indexPath.row]
- return cell;
- }
- }
SwiftyJSON
cell:
- //
- // OneCell.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/19.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- //
- import UIKit
- import SwiftyJSON
- import SDWebImage
- class OneCell: UITableViewCell {
- var jsonObj:JSON?{
- didSet{
- nameLabel.text = String(describing: jsonObj!["creator"]["nick"]) + "-" + String(describing: jsonObj!["city"])
- let str:String = String(describing: jsonObj!["creator"]["portrait"])
- picImgView.sd_setImage(with: URL.init(string: str), completed: nil)
- }
- }
- lazy var nameLabel:UILabel = {
- let la = UILabel.init()
- return la;
- }()
- lazy var picImgView:UIImageView = {
- let imgView = UIImageView.init()
- return imgView;
- }()
- override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
- super.init(style: style, reuseIdentifier: reuseIdentifier)
- setupUI()
- addCons()
- }
- func setupUI(){
- contentView.addSubview(nameLabel)
- contentView.addSubview(picImgView)
- }
- func addCons(){
- nameLabel.snp.makeConstraints { (make) in
- make.leftMargin.equalTo(contentView.snp.left).offset(10)
- make.rightMargin.equalTo(contentView.snp.right).offset(-10)
- make.topMargin.equalTo(contentView.snp.top).offset(10)
- make.height.equalTo(50)
- }
- picImgView.snp.makeConstraints { (make) in
- make.leftMargin.equalTo(contentView.snp.left).offset(10)
- make.topMargin.equalTo(nameLabel.snp.bottom).offset(20)
- make.height.width.equalTo(120)
- }
- }
- required init?(coder aDecoder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- }
SwiftyJSON
2.HandyJSON
C层:
- //
- // TabTwoVC.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/19.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- // HandyJSON -- https://github.com/alibaba/HandyJSON
- import UIKit
- import Alamofire
- import HandyJSON
- private let twoCellIdentifier = "twoCellIdentifier"
- class TabTwoVC: UIViewController {
- lazy var twoTableView:UITableView = {
- let tabView = UITableView.init(frame: UIScreen.main.bounds)
- tabView.delegate = self
- tabView.dataSource = self
- tabView.rowHeight = 220.0
- tabView.register(TwoCell.self, forCellReuseIdentifier: twoCellIdentifier)
- view.addSubview(tabView)
- return tabView
- }()
- var ary:[Dictionary<String, Any>] = []
- override func viewDidLoad() {
- super.viewDidLoad()
- Alamofire.request("http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1").responseJSON { (response) in
- let data:Dictionary<String,Any> = response.result.value as! Dictionary
- self.ary = data["lives"] as! [Dictionary<String, Any>]
- self.twoTableView.reloadData()
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
- extension TabTwoVC: UITableViewDelegate,UITableViewDataSource{
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return ary.count;
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: twoCellIdentifier, for: indexPath) as! TwoCell
- cell.model = JSONDeserializer.deserializeFrom(dict: ary[indexPath.row])
- return cell;
- }
- }
HandyJSON
cell:
- //
- // TwoCell.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/19.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- //
- import UIKit
- import SnapKit
- import SDWebImage
- class TwoCell: UITableViewCell {
- var model:TwoModel!{
- didSet{
- nameLabel.text = model.creator.nick + "-" + model.city
- let str = model.creator.portrait
- picImgView.sd_setImage(with: URL.init(string: str!), completed: nil)
- }
- }
- lazy var nameLabel:UILabel = {
- let la = UILabel.init()
- return la;
- }()
- lazy var picImgView:UIImageView = {
- let imgView = UIImageView.init()
- return imgView;
- }()
- override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
- super.init(style: style, reuseIdentifier: reuseIdentifier)
- setupUI()
- addCons()
- }
- func setupUI(){
- contentView.addSubview(nameLabel)
- contentView.addSubview(picImgView)
- }
- func addCons(){
- nameLabel.snp.makeConstraints { (make) in
- make.leftMargin.equalTo(contentView.snp.left).offset(10)
- make.rightMargin.equalTo(contentView.snp.right).offset(-10)
- make.topMargin.equalTo(contentView.snp.top).offset(10)
- make.height.equalTo(50)
- }
- picImgView.snp.makeConstraints { (make) in
- make.rightMargin.equalTo(contentView.snp.right).offset(-10)
- make.topMargin.equalTo(nameLabel.snp.bottom).offset(20)
- make.height.width.equalTo(120)
- }
- }
- required init?(coder aDecoder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- }
HandyJSON
model:
- //
- // Model.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/19.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- //
- import UIKit
- import HandyJSON
- struct TwoModel: HandyJSON {
- var city:String!
- var creator:TwoCreatorModel!
- }
- struct TwoCreatorModel: HandyJSON {
- var nick:String!
- var portrait:String!
- }
HandyJSON
3.ObjectMapper
C层:
- //
- // TabThreeVC.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/20.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- // ObjectMapper -- https://github.com/Hearst-DD/ObjectMapper
- import UIKit
- import Alamofire
- import ObjectMapper
- private let threeCellIdentifier = "threeCellIdentifier"
- class TabThreeVC: UIViewController {
- lazy var threeTableView:UITableView = {
- let tabView = UITableView.init(frame: UIScreen.main.bounds)
- tabView.delegate = self
- tabView.dataSource = self
- tabView.rowHeight = 220.0
- tabView.register(ThreeCell.self, forCellReuseIdentifier: threeCellIdentifier)
- return tabView
- }()
- var ary:[Dictionary<String, Any>] = []
- override func viewDidLoad() {
- super.viewDidLoad()
- view.addSubview(threeTableView)
- Alamofire.request("http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1").responseJSON { (response) in
- let data:Dictionary<String,Any> = response.result.value as! Dictionary
- self.ary = data["lives"] as! [Dictionary<String, Any>]
- self.threeTableView.reloadData()
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
- extension TabThreeVC: UITableViewDelegate,UITableViewDataSource{
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return ary.count;
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: threeCellIdentifier, for: indexPath) as! ThreeCell
- cell.model = Mapper<ThreeModel>().map(JSON: ary[indexPath.row])
- return cell;
- }
- }
ObjectMapper
cell:
- //
- // ThreeCell.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/20.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- //
- import UIKit
- import SnapKit
- import SDWebImage
- class ThreeCell: UITableViewCell {
- var model:ThreeModel!{
- didSet{
- nameLabel.text = model.creator!.nick! + model.city!
- let str = model.creator!.portrait
- picImgView.sd_setImage(with: URL.init(string: str!), completed: nil)
- }
- }
- lazy var nameLabel:UILabel = {
- let la = UILabel.init()
- la.textAlignment = .center
- return la;
- }()
- lazy var picImgView:UIImageView = {
- let imgView = UIImageView.init()
- return imgView;
- }()
- override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
- super.init(style: style, reuseIdentifier: reuseIdentifier)
- setupUI()
- addCons()
- }
- func setupUI(){
- contentView.addSubview(nameLabel)
- contentView.addSubview(picImgView)
- }
- func addCons(){
- nameLabel.snp.makeConstraints { (make) in
- make.leftMargin.equalTo(contentView.snp.left).offset(10)
- make.rightMargin.equalTo(contentView.snp.right).offset(-10)
- make.topMargin.equalTo(contentView.snp.top).offset(10)
- make.height.equalTo(50)
- }
- picImgView.snp.makeConstraints { (make) in
- make.center.equalTo(contentView.snp.center)
- make.height.width.equalTo(120)
- }
- }
- required init?(coder aDecoder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- }
ObjectMapper
model:
- //
- // ThreeModel.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/20.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- //
- import UIKit
- import ObjectMapper
- struct ThreeModel: Mappable {
- var city:String!
- var creator:ThreeCreatorModel!
- mutating func mapping(map: Map) {
- city <- map["city"]
- creator <- map["creator"]
- }
- init?(map: Map) {
- }
- }
- struct ThreeCreatorModel: Mappable {
- var nick:String!
- var portrait:String!
- mutating func mapping(map: Map) {
- nick <- map["nick"]
- portrait <- map["portrait"]
- }
- init?(map: Map) {
- }
- }
ObjectMapper
4.swift4.0 Codable
C层:
- //
- // TabFourVC.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/20.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- // 自家孩子 swift4.0 Codable
- import UIKit
- import Alamofire
- private let fourCellIdentifier = "fourCellIdentifier"
- class TabFourVC: UIViewController {
- lazy var fourTableView:UITableView = {
- let tabView = UITableView.init(frame: UIScreen.main.bounds)
- tabView.delegate = self
- tabView.dataSource = self
- tabView.rowHeight = 220.0
- tabView.register(FourCell.self, forCellReuseIdentifier: fourCellIdentifier)
- view.addSubview(tabView)
- return tabView
- }()
- var model:FourModel!
- override func viewDidLoad() {
- super.viewDidLoad()
- Alamofire.request("http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1").responseData { (data) in
- self.model = try! JSONDecoder().decode(FourModel.self, from: data.result.value!)
- self.fourTableView.reloadData()
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
- extension TabFourVC: UITableViewDelegate,UITableViewDataSource{
- func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
- return model.lives.count;
- }
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- let cell = tableView.dequeueReusableCell(withIdentifier: fourCellIdentifier, for: indexPath) as! FourCell
- cell.model = model.lives[indexPath.row]
- return cell;
- }
- }
Codable
cell:
- //
- // FourCell.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/20.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- //
- import UIKit
- import SnapKit
- import SDWebImage
- class FourCell: UITableViewCell {
- var model:FourLivesModel!{
- didSet{
- nameLabel.text = model.city + model.creator.nick
- let str = model.creator.portrait
- picImgView.sd_setImage(with: URL.init(string: str), completed: nil)
- }
- }
- lazy var nameLabel:UILabel = {
- let la = UILabel.init()
- la.textAlignment = .center
- la.backgroundColor = UIColor.red
- return la;
- }()
- lazy var picImgView:UIImageView = {
- let imgView = UIImageView.init()
- return imgView;
- }()
- override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
- super.init(style: style, reuseIdentifier: reuseIdentifier)
- setupUI()
- addCons()
- }
- func setupUI(){
- contentView.addSubview(nameLabel)
- contentView.addSubview(picImgView)
- }
- func addCons(){
- picImgView.snp.makeConstraints { (make) in
- make.center.equalTo(contentView.snp.center)
- make.height.width.equalTo(120)
- }
- nameLabel.snp.makeConstraints { (make) in
- make.leftMargin.equalTo(contentView.snp.left).offset(10)
- make.rightMargin.equalTo(contentView.snp.right).offset(-10)
- make.topMargin.equalTo(picImgView.snp.bottom).offset(10)
- make.height.equalTo(50)
- }
- }
- required init?(coder aDecoder: NSCoder) {
- fatalError("init(coder:) has not been implemented")
- }
- }
Codable
model:
- //
- // FourModel.swift
- // myDemo
- //
- // Created by Shaoting Zhou on 2017/12/20.
- // Copyright © 2017年 Shaoting Zhou. All rights reserved.
- //
- import UIKit
- struct FourModel: Codable {
- var error_msg:String
- var lives:[FourLivesModel]
- }
- struct FourLivesModel: Codable {
- var city:String
- var creator:FourCreatorModel
- }
- struct FourCreatorModel: Codable {
- var nick:String
- var portrait:String
- }
Codable
基本的效果都长这样:
GitHub地址: https://github.com/pheromone/swift_study
swift4.0 数据转模型的更多相关文章
- Thinkphp5.0 的使用模型Model删除数据
Thinkphp5.0 的使用模型Model删除数据 一.使用destory()删除数据 //删除id为3的记录 $res = User::destroy(3); //返回影响的行数 dump($re ...
- Thinkphp5.0 的使用模型Model更新数据
Thinkphp5.0 的使用模型Model更新数据 (1)使用update()方法进行更新数据 一.where条件写在更新数据中 (这种情况更新的数据,必须含主键) $res = User::upd ...
- Thinkphp5.0 的使用模型Model添加数据
Thinkphp5.0 的使用模型Model添加数据 使用create()方法添加数据 $res = TestUser::create([ 'name' => 'zhao liu', 'pass ...
- R_针对churn数据用id3、cart、C4.5和C5.0创建决策树模型进行判断哪种模型更合适
data(churn)导入自带的训练集churnTrain和测试集churnTest 用id3.cart.C4.5和C5.0创建决策树模型,并用交叉矩阵评估模型,针对churn数据,哪种模型更合适 决 ...
- pytorch入门2.0构建回归模型初体验(数据生成)
pytorch入门2.x构建回归模型系列: pytorch入门2.0构建回归模型初体验(数据生成) pytorch入门2.1构建回归模型初体验(模型构建) pytorch入门2.2构建回归模型初体验( ...
- ThinkPHP 学习笔记 ( 三 ) 数据库操作之数据表模型和基础模型 ( Model )
//TP 恶补ing... 一.定义数据表模型 1.模型映射 要测试数据库是否正常连接,最直接的办法就是在当前控制器中实例化数据表,然后使用 dump 函数输出,查看数据库的链接状态.代码: publ ...
- kafka 日常使用和数据副本模型的理解
kafka 日常使用和数据副本模型的理解 在使用Kafka过程中,有时经常需要查看一些消费者的情况.Kafka健康状况.临时查看.同步一些数据,又由于Kafka只是用来做流式存储,又没有像Mysql或 ...
- 胖子哥的大数据之路(9)-数据仓库金融行业数据逻辑模型FS-LDM
引言: 大数据不是海市蜃楼,万丈高楼平地起只是意淫,大数据发展还要从点滴做起,基于大数据构建国家级.行业级数据中心的项目会越来越多,大数据只是技术,而非解决方案,同样面临数据组织模式,数据逻辑模式的问 ...
- ThinkPHP 数据库操作之数据表模型和基础模型 ( Model )
一.定义数据表模型 1.模型映射 要测试数据库是否正常连接,最直接的办法就是在当前控制器中实例化数据表,然后使用 dump 函数输出,查看数据库的链接状态.代码: public function te ...
随机推荐
- redmine
redmine直接复制图片 https://github.com/thorin/redmine_image_clipboard_paste
- 记一次tomcat运行起来了但是项目没起来的问题
解决办法是: 先是tomcat的conf文件夹下的servel.xml中这两个值改成false. 然后重新运行maven的package打包,再运行项目就行了.
- mac版mysql配置
开始下载 我选择的是最后一个dmg格式的安装包,点击download,会出现让我们注册登陆的界面,点击最下面的No thanks,just take me to downloads!直接进行下载即可: ...
- oracle性能优化之awr分析
oracle性能优化之awr分析 作者:bingjava 最近某证券公司系统在业务期间系统运行缓慢,初步排查怀疑是数据库存在性能问题,因此导出了oracle的awr报告进行分析,在此进行记录. 导致系 ...
- wait和sleep的区别
wait是线程永久等待,只有调用notify才能进行唤醒 sleep是等待指定的时间,自动唤醒
- fastjson对象转为json字符串日期格式变为时间戳问题
今天尝试将map集合转为json对象时遇到一个问题.map中的value为日期格式如"2019-03-01",在使用JSONObject.toJSON(map).toString( ...
- Rhino模型制作——京东狗(练习网格切割)
我最近做了一个京东狗的模型,我先把渲染好的模型给大家看一下. 别看这个模型很复杂,其实京东狗的模型是网上找的,我只是做了一个上面的洞.不过我告诉大家Rhino的下载地址:http://www.xuex ...
- React 实战系列:模块化
本系列以实战为主,通过一个 TODO 应用来学习深入 React. 学习无捷径,唯一的办法就是 coding!coding!coding! 如有不足之处,欢迎大家批评指正,共同进步! 言毕,开始撸
- 四、Linux的常用命令
linux常用命令可以参考这位前辈的:https://www.cnblogs.com/gaojun/p/3359355.html 这篇博文介绍的比较详细!
- K2百家讲坛 | 越秀地产:K2为房企数字化转型带来更多可能
随着数字化经济时代的到来,房地产行业逐渐形成了新的竞争和市场格局,房企要在此背景下实现稳步发展,需要由原本的粗放式管理逐渐向集团性管理.精细化管控转变,这对房企的经营发展战略和业务管理方式都提出了不小 ...