Apple recommends MVC architecture for development and is undeniably more common architecture. MVC segregate code in three parts — logic/data, view(GUI) and model. Today we’ll talk about how to write models while minimising boilerplate code.

苹果公司推荐使用MVC架构进行开发,并且毫无疑问,它是更常见的架构。 MVC将代码分为三部分-逻辑/数据,视图(GUI)和模型。 今天,我们将讨论如何在最小化样板代码的同时编写模型。

Models are representations of data that flows through your application. For example, we get unordered and unreadable junk from servers and that too in huge quantity. We know we have some edible data in the junk and we need a way to filter it out. Moreover model has knowledge of a domain(say User), user’s data is used multiple times in an application. Same user model can be used at all places.

模型是流经您的应用程序的数据的表示。 例如,我们从服务器中收到无序且难以读取的垃圾,并且数量也很大。 我们知道垃圾中有一些可食用的数据,我们需要一种过滤数据的方法。 而且模型具有领域知识(比如说用户),用户的数据在应用程序中被多次使用。 可以在所有地方使用相同的用户模型。

Models are not concerned about UI and presentation of data and not even the logic behind operations. In simple words they are data containers, having data organised as objects with some properties. The view and the controller communicate with each other indirectly through these data containers(model).

模型不关心UI和数据表示,甚至不关心操作背后的逻辑。 简而言之,它们是数据容器,将数据组织为具有某些属性的对象。 视图和控制器通过这些数据容器(模型)间接相互通信。

To understand it better let’s have an eye on some code.

为了更好地理解它,让我们看一些代码。

Lets create a demo JSON having with object named organisation and having three associated properties

让我们创建一个演示JSON ,该JSON具有名为organization的对象并具有三个关联的属性

{"organization" : {"organization_name" : "XYZ Enterprises","organization_location" : "Lucknow, India","established_year":2012}
}

We will parse the JSON first using the conventional model approach. Next, we do the same task using Codable.

我们将首先使用常规模型方法解析JSON。 接下来,我们使用Codable执行相同的任务。

老派方法 (Old School Approach)

Consider a model named Organization with some properties:

考虑一个名为Organization的模型,该模型具有一些属性:

class Organization {orgName: StringorgLocation: Stringestablished: Int}

Organisation has three properties — orgName of String type, orgLocation is again of String type. and established year of Integer type.

Organisation有三个属性- orgNameString类型, orgLocation又是String类型。 并established Integer类型的年份。

Organisation properties has to be initialised. We will initialise it using init() method:

组织属性必须初始化。 我们将使用init()方法对其进行init()

class Organization {
orgName: String
orgLocation: String
established: Intinit?(orgName: String, orgLocation: String, established: Int) {// Initialize stored properties.
self.orgName = orgName
self.orgLocation = orgLocation
self.established = established}
}

Let’s see a use case of model: Let suppose we have response in JSON format from the server. We first have to parse JSON and set it in our model class.

让我们看一下模型的用例:假设我们有来自服务器的JSON格式的响应。 我们首先必须解析JSON并将其设置在模型类中。

var organization: Organization?
let jsonData: Data = /* get your json data from server or local json file */
let jsonArray = try [JSONSerialization.jsonObject(with: jsonData) as? [NSDictionary] let organizationName = jsonArray["organization_name"] as? String
let organizationLocation = jsonArray["organization_location"] as? String
let established = jsonArray["established_year"] as? Int
user(orgName: organizationName, orgLocation: organizationLocation, age: established)

That’s general way parsing json in models.Now will do the same task but now using codable and will talk about the differences between these two approaches.

这是解析模型中json的一般方法,现在将执行相同的任务,但现在使用可codable ,并将讨论这两种方法之间的差异。

使用可编码的更清洁方法 (Cleaner Approach using codable)

Codable is collective name given to protocols Encodable and decodable. In this demo we only need decodable. We write codable model as follows:

Codable是协议可编码和可解码的总称。 在此演示中,我们只需要可解码的即可。 我们编写可codable模型如下:

And thats it!.Here, names of the parameters matches the json keys. If you want to follow your favourite naming convention then you can use coding keys. Coding keys helps you keep your code readable. You can implement coding keys like this

就是这样!。在这里,参数名称与json键匹配。 如果要遵循自己喜欢的命名约定,则可以使用编码键。 编码键可帮助您保持代码的可读性。 您可以像这样实现编码键

Now we will decode json data.

现在我们将解码json数据。

let jsonData: Data = /* get your json data from server or local json file */
let organization = JSONDecoder().decode(Organization.self, from: jsonData)
print("Organization Name: - \(organization.orgName) \n")
print("Organization location: - \(organization.orgName) \n")
print("Year of foundation: - \(organization.established)")

Above snippet simply prints parsed data on console. The output looks like this

以上代码段仅在控制台上打印已解析的数据。 输出看起来像这样

Organization Name: - XYZ Enterprises
Organization location - Lucknow, India
Year of foundation: - 2012

Decodable, clearly is winner if we compare above two approaches of JSON parsing.

如果我们比较上述两种JSON解析方法,那么Decodable显然是赢家。

!!! HAPPY CODING !!!

!!! 快乐编码!

Thank you for reading, please hit the recommend icon if like this collection. Questions or Doubts? Leave them in the comment.

感谢您的阅读,如果喜欢此收藏,请点击“推荐”图标。 有疑问或疑问吗? 将它们留在评论中。

翻译自: https://medium.com/swiftcommmunity/codables-a-better-way-parse-data-in-swift-e08015f4ee4e


http://www.taodudu.cc/news/show-4590126.html

相关文章:

  • 新型高科技口罩即将成为一种身份象征
  • 【NLP】第12章 检测客户情绪以做出预测
  • 如何高效编写Go单元测试(一)
  • iphone6 续航 测试软件,7款iPhone测试iOS13.6电池续航:结果耗电更严重了?
  • 美国一男子起诉苹果:称 iPhone 6 电池存在缺陷导致爆炸
  • iPhone 电池的正确激活与使用方式
  • 如何维持手机电池寿命_七大技巧让你的iPhone电池延长使用寿命
  • 0110 - 给 iPhone 6 换了电池
  • iphone7plus计算机,iPhone 7 Plus真实详尽评测-电池篇
  • 6个iPhone电池保养小技巧,错过就亏大啦!
  • iphone6 续航 测试软件,iPhone 6s电池续航能力究极测试 1715毫安电池逆天了
  • 王三金的电影清单
  • 2021年熔化焊接与热切割考试题库及熔化焊接与热切割复审考试
  • 2021年熔化焊接与热切割报名考试及熔化焊接与热切割最新解析
  • HTML进阶- 4.6 补充一些不常用的元素
  • redis分布式锁实践 并实现看门狗锁续期机制
  • 身后的那条狗没了
  • ChatGPT到底是个啥 - 它甚至会和狗说话
  • 2022年9月大学英语B统考题库网考大学英语B试题
  • 2018仁爱英语7年级下册U6T2学科讲义(有答案)
  • springboot和redis处理页面缓存
  • Java设计模式【1】
  • 我们的23种设计模式(四)
  • 被撕裂的中国二
  • 密歇根大学计算机硕士学制,密歇根大学安娜堡分校学专业设置及学制介绍
  • 密歇根安娜堡计算机排名,密歇根大学安娜堡分校计算机科学与工程研究生最新专业排名...
  • 密歇根安娜堡大学的计算机科学教授,密歇根大学安娜堡分校计算机科学与工程研究生offer及申请要求...
  • Python程序设计题库——第二章
  • 2021年电工(初级)报名考试及电工(初级)理论考试
  • 计算智能——遗传算法解决TSP问题实验

codables一种更好的方式快速解析数据相关推荐

  1. 智慧城市综合管理平台,以一种更智慧的方式促进城市运行

    智慧城市综合管理平台是在新一代信息技术加速发展的背景下,充分运用大数据.云计算.物联网等技术手段对公共服务.社会管理.产业运作等活动的各种需求做出智能响应,将生产.商业.运输.通信.医疗等城市运行的各 ...

  2. 【你不知道的事】JavaScript 中用一种更先进的方式进行深拷贝:structuredClone

    你是否知道,JavaScript中有一种原生的方法来做对象的深拷贝? 本文我们要介绍的是 structuredClone 函数,它是内置在 JavaScript 运行时中的: const calend ...

  3. 数据湖:用以分析客户数据的一种更好的方式

    "我们的目标是尽可能快的将数据植入我们的业务,使得我们能够不断发掘出新的业务机会."The Weather Company的执行副总裁首席技术官兼首席信息官布莱森·克勒表示说.在任 ...

  4. Zilliz 顾钧:开源是协调技术供应商、开发者和用户之间利益的一种更健康的方式 I OpenTEKr 大话开源 Vol.2

    /// 大话开源 /// 「大话开源」是 OpenTEKr 旗下对话国内外开放科技界思想引领者(Open Tech Thoughtleaders)的访谈节目,致力于捕捉大咖们的开源精髓,为从业者和门外 ...

  5. pythonjson实例_python:JSON的两种常用编解码方式实例解析

    概念 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写.在日常的工作中,应用范围极其广泛.这里就介绍python下它的两种编解码方法: 使 ...

  6. 基于uFUN开发板的心率计(一)DMA方式获取传感器数据

    前言 从3月8号收到板子,到今天算起来,uFUN到手也有两周的时间了,最近利用下班后的时间,做了个心率计,从单片机程序到上位机开发,到现在为止完成的差不多了,实现很简单,uFUN开发板外加一个Puls ...

  7. 使用Chrome快速实现数据的抓取(四)——优点

    些一个抓取WEB页面的数据程序比较简单,大多数语言都有相应的HTTP库,一个简单的请求响应即可,程序发送Http请求给Web服务器,服务器返回HTML文件.交互方式如下: 在使用DevProtocol ...

  8. gazebo 直接获取传感器数据_基于uFUN开发板的心率计(一)DMA方式获取传感器数据...

    前言 从3月8号收到板子,到今天算起来,uFUN到手也有两周的时间了,最近利用下班后的时间,做了个心率计,从单片机程序到上位机开发,到现在为止完成的差不多了,实现很简单,uFUN开发板外加一个Puls ...

  9. angularjs 获取复选框的值_基于uFUN开发板的心率计(一)DMA方式获取传感器数据

    前言 从3月8号收到板子,到今天算起来,uFUN到手也有两周的时间了,最近利用下班后的时间,做了个心率计,从单片机程序到上位机开发,到现在为止完成的差不多了,实现很简单,uFUN开发板外加一个Puls ...

最新文章

  1. 浙江大学医学院附属儿童医院倪艳组招聘博士后和科研助理-肠道微生物和代谢方向...
  2. 取一定范围内随机小数 c_随机振动测试中的常见试验条件有哪些?
  3. mysql 主从数据库设置方法
  4. android实现简单的聊天室
  5. PX4 FMU [7] rgbled [转载]
  6. windows高精度计数器
  7. 中国省份名称的映射字典
  8. c语言工程师专业分析,一个资深c语言工程师说如何学习c语言.pdf
  9. con和com开头单词
  10. 王之泰201771010131《面向对象程序设计(java)》第十四周学习总结
  11. 处理样本分布不平衡,偏斜比较厉害的方法总结
  12. LUMION PureGlass纯正玻璃材质新功能应用
  13. 中国高校外语慕课平台职场英语期末考试答案
  14. SAP采购申请中数量/单价/价格单位/总价的填写图示
  15. 360插件化方案RePlugin学习笔记-插件使用宿主中的类
  16. “玻璃大王”曹德旺捐资100亿办大学!幼年失学的他要打造理工科研究型大学...
  17. 那些逝去的岁月-性格分析
  18. C# hashTable的遍历【2种方法】与排序【3种方法】
  19. 图像特征点、投影变换与图像拼接
  20. 【问题篇】免费下载使用RDM

热门文章

  1. 百度知道推广,常见的3个小窍门
  2. 开发 Web 应用程序
  3. 基于Seq2Seq的GRU时间序列预测Python程序
  4. 安道拓Adient EDI 830物料需求预测报文详解
  5. java实现PEKS_JAVA线程基础
  6. crontab python不生效_crontab 中 python 脚本执行失败的解决方法
  7. 最新Nikon镜头序列号查询,镜头产量估算2010.1.26更新
  8. Blogbus适用的日志发布工具【超级写手】
  9. 流畅的python 14章可迭代的对象、迭代器 和生成器
  10. CKEditor5+vue3使用以及如何添加新工具栏