swift 可选链

Swift Optional Chaining is a very useful feature. Optionals are a type in Swift that wrap primitive types and are typically used for preventing null values. For more details on Optionals refer this tutorial before proceeding ahead.

Swift Optional Chaining是一个非常有用的功能。 可选参数是Swift中包装原始类型的类型,通常用于防止空值。 有关Optional的更多详细信息,请在继续操作之前参考本教程。

Swift可选链 (Swift Optional Chaining)

Optional Chaining is the process of chaining calls on optional values such that it handles the unwrapping gracefully and concisely without giving runtime errors. As the name says, it chains multiple queries together.

可选链接是对可选值链接调用的过程,以便它可以优雅,简洁地处理展开操作,而不会产生运行时错误。 顾名思义,它将多个查询链接在一起。

But the same thing is achievable using if let,guard let and implicit unwrapping too.

但是使用if letguard let和隐式解包也是可以实现的。

那么,对“可选链接”有何需求? (What’s the need for Optional Chaining then?)

Let’s look at an example in Playground first without bringing Optional Chaining.

让我们先来看一下Playground中的示例,而没有带来“可选链接”。

没有可选链接 (Without Optional Chaining)

Let’s assume we have the following classes:

假设我们有以下类:

class University {var city: City?var universityName: String = "Indian Institute of Technology"
}class City{var cityName: String?var college: College?}class College{var discplines = [Discpline?]()var numberOfStreams : Int{return discplines.count}}class Discpline{var discplineName: String?var student : Student?
}class Student{var name: String?var discpline : Discplineinit(currentDiscpline: Discpline) {self.discpline = currentDiscpline}func printDetails() ->String  {return "Student Details:\n Name:\(name ?? "Na") \n Discpline: \(discpline.discplineName ?? "NA")"}
}

Every class contains an instance of the below class. All instances are defined as optionals.
College class holds an array of Discpline class objects.

每个类都包含以下类的实例。 所有实例均定义为可选。
College班级拥有一系列Discpline班级对象。

Let’s instantiate each of these classes.

让我们实例化每个这些类。

var university = University()
var myCity = City()
myCity.cityName = "Bangalore"
var myCollege = College()
var csDiscpline = Discpline()
csDiscpline.discplineName = "Computer Science"
var meDiscpline = Discpline()
meDiscpline.discplineName = "Mechanical Engineering"
myCollege.discplines = [csDiscpline,meDiscpline]var myStudent = Student(currentDiscpline: csDiscpline)
myStudent.name = "Anupam"

Using Implicit Unwrapping
Let’s get and retrieve properties and functions from the classes using implicit unwrapping (!).

使用隐式展开
让我们使用隐式展开(!)从类中获取和检索属性和函数。

university.city = myCity
university.city!.college = myCollege
university.city!.college!.discplines = [csDiscpline,meDiscpline]
university.city!.college!.discplines[0]!.student = myStudent
var finalString = university.city!.college!.discplines[0]!.student!.printDetails()

This looks okay. But we know from the Optionals in Swift tutorial that implicit unwrapping can lead to runtime crashes since it unwraps the optional without checking if it’s nil or not.

看起来还好 但是我们从Swift的Optionals教程知道,隐式展开可能会导致运行时崩溃,因为它会在不检查nil是否为零的情况下将其展开。

In the above code, if we set myStudent as nil, it’ll lead to a CRASH.

在上面的代码中,如果将myStudent设置为nil,它将导致CRASH

university.city!.college!.discplines[0]!.student = nil
var finalString = university.city!.college!.discplines[0]!.student!.printDetails() //crash since student is nil

Let’s try using if let/if var.

让我们尝试使用if let / if var

if var uCity = university.city
{uCity = myCityif var uCollege = uCity.college{uCollege = myCollegeuCollege.discplines = [csDiscpline,meDiscpline]if var uDiscpline = uCollege.discplines[0]{if var uStudent = uDiscpline.student{   uStudent = myStudentprint(uStudent.printDetails())}}}
}

Too much of nesting! And that too just to set values and print the result in a very basic code with hardly a few properties in each class.

嵌套太多! 这也仅仅是为了设置值并以非常基本的代码打印结果,而每个类中几乎没有几个属性。

This is inefficient.

这是低效的。

Using guard var
Let’s do the same using guard var.

使用guard var
让我们使用guard var做同样的事情。

func usingGuard(){
guard var uCity = university.city else{print("City is nil")return
}
uCity = myCityguard var uCollege = uCity.college else{print("College is nil")return
}
uCollege = myCollege
uCollege.discplines = [csDiscpline,meDiscpline]guard var uDiscpline = uCollege.discplines[0] else{print("Discpline is nil")return
}guard var uStudent = uDiscpline.student else{print("Student is nil")return
}
uStudent = myStudent
print(uStudent.printDetails())
}usingGuard()
//prints
//Student Details:
// Name:Anupam
// Discpline: Computer Science

This is better than if var but still too many conditional checks. Implicit wrapping was concise and crisp but dangerous since it didn’t check the optional value before unwrapping.

这比var更好,但是仍然有太多条件检查。 隐式包装简洁明了,但很危险,因为它在展开之前并未检查可选值。

This is where Optional Chaining comes to our rescue.

这是可选链接为我们提供帮助的地方。

It’s an alternative and better form of forced unwrapping.

这是强制展开的另一种更好的形式。

In optional chaining, we just need to replace !. with ?..

在可选链接中,我们只需要替换!.?.

可选链接如何工作 (How does Optional Chaining work)

Optional Chaining is done over optional values. It returns the desired value wrapped as an Optional. If the optional is nil, it returns an Optional(nil). Optional Chaining always gives you an optional thereby eliminating the chance of runtime crashes.

可选链接是在可选值上完成的。 它返回包装为Optional的所需值。 如果optional为nil,则返回Optional(nil) 。 可选链接始终为您提供可选选项,从而消除了运行时崩溃的机会。

Hence two things:

因此有两件事:

  • If the type that’s been retrieved through Optional Chaining is not optional, then after the optional chaining is done, it becomes optional.如果通过“可选链接”检索的类型不是可选的,则在完成可选链接后,它将变为可选。
  • If the type was already optional, it’ll stay optional only. It’ll not get nested like Optional(Optional(String)).如果类型已经是可选的,则它将仅保持可选。 它不会像Optional(Optional(String))那样嵌套。

使用可选链接实施 (Implementation With Optional Chaining)

The below code has optional chaining implemented.

以下代码实现了可选的链接。

university.city = myCity
university.city?.college = myCollege
university.city?.college?.discplines = [csDiscpline,meDiscpline]
university.city?.college?.discplines[0]!.student = myStudent
var finalString = university.city?.college?.discplines[0]?.student?.printDetails()
print(finalString)

Now printDetails() was defined to return a String.

现在,定义了printDetails()以返回String

Does it?
NO.

可以?
没有。

It returns an Optional(String) since the Optional Chaining wraps the returned value with an optional.

它返回一个Optional(String),因为Optional Chaining用可选的包装了返回的值。

通过可选链接访问下标调用 (Accessing Subscript calls through optional chaining)

Change the Discpline class to:

将Discpline类更改为:

class College{var discplines = [Discpline?]()var numberOfStreams : Int{return discplines.count}subscript(i: Int) -> Discpline? {get {return discplines[i]}set {discplines[i] = newValue}}}

Thanks to subscripts we can get rid of the discpline object invocation.

多亏了下标,我们可以摆脱纪律对象的调用。

if let discpline0 = university.city?.college?[0]?.discplineName
{print(discpline0)
}

Note: When accessing a subscript on an optional value through optional chaining, you place the question mark before the subscript’s brackets, not after. Hence we’d done college?[0]. It gets the first discipline.

注意:通过可选链访问可选值上的下标时,将问号放在下标的括号之前,而不是之后。 因此,我们上过大学吗?[0]。 它是第一门学科。

This brings an end to this tutorial. You can download the Swift Playground file from the below link.

本教程到此结束。 您可以从以下链接下载Swift Playground文件。

OptionalChaining.playground.

OptionalChaining.playground 。

Reference: Apple Docs

参考: Apple Docs

翻译自: https://www.journaldev.com/19587/swift-optional-chaining

swift 可选链

swift 可选链_Swift可选链相关推荐

  1. swift可选类型_Swift可选

    swift可选类型 Swift Optional is a very important underlying concept in Swift programming. Optional is so ...

  2. Swift之深入解析可选链的功能和使用

    一.什么是可选链? 可选链(Optional Chaining)是一种可以请求和调用属性.方法和子脚本的过程,用于请求或调用的目标可能为nil. 可选链返回两个值: 如果目标有值,调用就会成功,返回该 ...

  3. 基于区块链的健康链系统设计与实现(2)区块链平台Web服务器

    2.2 区块链平台分析 Bitcoin(比特币)作为区块链技术的起源,是目前发展最成熟的开源区块链平台之一,拥有大量的开发人员和活跃的开发社区.Ethereum(以太坊)核心是支持智能合约的EVM(以 ...

  4. 以太坊《私有链和联盟链的机会与挑战》报告

    以太坊平台评估 私有链和联盟链的机会与挑战 作者:Vitalik Buterin  翻译:万向区块链实验室/ChinaLedger 联盟  排版/校对:区块链铅笔(ChainB.com) (注:本文属 ...

  5. 一文说清“链上”和“链下”

    什么是"链上"和"链下" 区块"链"的链,包含"数据链"和"节点链".数据链指用链式结构组织区块数据 ...

  6. 咖说丨一文说清“链上”和“链下”

    " 收集一众行业大咖观点,探索区块链商业及应用.百家争鸣.百花齐放,说理.解密.预测和八卦,了解行业内幕,看咖说就够了! 投稿请联系 :tougao@conflux-chain.org 本文 ...

  7. 区块链中的“链上”和“链下”

    原标题:一文读懂"链上"和"链下" 什么是"上链"?什么数据和逻辑应该"上链"?文件能不能上链?链上能不能批量查数据?& ...

  8. 区块链BaaS云服务(16)天德链TDBC“金丝猴链”

    1. 定义 两个参与链之间,可以有多条中间链,每两个机构之间都可以通过中间链进行跨链交易.每条链维护自己的一致性,链与链之间的一致性由一个完全分布式的机制来维持,而不需要由一个中间组织来管理. 1.1 ...

  9. 沃尔玛中国将采用唯链雷神区块链追踪食品供应链

    点击上方"蓝色字"可关注我们! 暴走时评:据报道,沃尔玛中国计划采用唯链(VeChain)的雷神(Thor)区块链追踪食品供应链,与唯链.PwC.内蒙古科尔沁牛业以及中国连锁经营协 ...

最新文章

  1. 认证登录时代来临,主流验证登录方式盘点
  2. 【mysql】使用tpcc-mysql进行压力测试
  3. 国产linux 中标麒麟安装.net core sdk
  4. 组策略链接顺序优先级
  5. chrome打开清除浏览数据窗口快捷键
  6. HDU 1698 Just a Hook 线段树
  7. Ubuntu 16.04 用apt-get来安装Java
  8. 常用类 (六) ----- String类与字符串
  9. php设置路径别名,设置别名php = / bin / php56,但今天它已恢复为原始路径:/ bin / php...
  10. ui分离的进程 如何查找窗口句柄_如何使用 Linux screen
  11. catia怎么将特征参数化_catia 怎么做参数化设计
  12. 美团java后端面试题目_美团笔试题(Java后端5题2小时)
  13. 【方案分享】2022虎年新春潮玩嘉年华活动策划方案:我们超虎的.pptx(附下载链接)...
  14. python3 解压7z文件
  15. php错误处理视频教程,PHP错误与异常调试视频教程资源分享
  16. shell脚本——正则表达式(包含grep详细介绍及应用)
  17. 字节校招面试题分享,别人已经开始面试了,你不会还没有准备吧?
  18. 学3d建模和计算机编程,超好用的3D建模软件全科普,想要学好建模的你千万别错过!...
  19. 初探强化学习(10)强化学习中的一些术语(non-stationray,sample efficiency,planning和Learnin,Reward,off-policy和on-policy )
  20. Epoll的本质(内部实现原理)

热门文章

  1. 理解JavaScript函数(函数和对象的区别和联系)
  2. C#获取文件夹下的所有文件名
  3. [USACO5.1] Musical Themes
  4. java BitSet2
  5. html5 教程网站
  6. HDU 4597 Play Game
  7. 关于多维数组编码与解码的问题
  8. POJ 3984 迷宫问题 (Dijkstra)
  9. 该网站可能含有恶意软件,有可能会危害您的电脑 清除办法
  10. 数据结构上机实践第九周项目1 - 二叉树算法库