swift学习笔记之-可选链式调用
//可选链式调用
import UIKit
/*可选链式调用(Optional Chaining)
1.在可选值上请求和调用该可选值的属性、方法及下标的方法,如果可选值有值,那么调用就会成功,返回可选类型值,如果可选值是nil,那么调用将返回nil,多个调用可以连接在一起形成一个调用链,如果其中任何一个节点为nil,整个调用链都会失败,即返回nil;(而强制展开它的值是"!",有值则返回该值,无值则会触发运行时错误)
2.通过在想调用的属性、方法、或下标的可选值(optional value)后面放一个问号"?"
3.可选链式调用返回的是可选类型值,它的返回结果与原本的返回结果具有相同的类型,但是被包装成了一个可选值
访问可选类型的下标:
var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
在方法的可选返回值上进行可选链式调用,在方法的圆括号后面加上问号
let beginsWithThe = john.residence?.address?.buildingIdentifier()?.hasPrefix("The")
在方法的圆括号后面加上问号是因为你要在buildingIdentifier()方法的可选返回值上进行可选链式调用,而不是方法本身。
*/
class Person {
var residence: Residence?
}
class Residence {
var rooms = [Room]()
var numberOfRooms: Int {
return rooms.count
}
subscript(i: Int) -> Room {
get {
return rooms[i]
}
set {
rooms[i] = newValue
}
}
func printNumberOfRooms() {
print("The number of rooms is \(numberOfRooms)")
}
var address: Address?
}
class Room {
let name: String
init(name: String) { self.name = name }
}
class Address {
var buildingName: String?
var buildingNumber: String?
var street: String?
func buildingIdentifier() -> String? {
if buildingName != nil {
return buildingName
} else if buildingNumber != nil && street != nil {
return "\(buildingNumber) \(street)"
} else {
return nil
}
}
}
let john = Person()
if let roomCount = john.residence?.numberOfRooms { //因为john.residence为nil,调用失败,返回nil
print("John's residence has \(roomCount) room(s).")
} else {
print("Unable to retrieve the number of rooms.")
}
// 打印 “Unable to retrieve the number of rooms.”
let someAddress = Address()
someAddress.buildingNumber = "29"
someAddress.street = "Acacia Road"
john.residence?.address = someAddress //因为john.residence当前为nil,调用失败,等号右侧的代码不会被执行,赋值失败
if john.residence?.printNumberOfRooms() != nil { //调用方法失败,返回nil,如果成功则返回void?
print("It was possible to print the number of rooms.")
} else {
print("It was not possible to print the number of rooms.")
}
// 打印 “It was not possible to print the number of rooms.”
if (john.residence?.address = someAddress) != nil {
print("It was possible to set the address.")
} else {
print("It was not possible to set the address.")
}
// 打印 “It was not possible to set the address.”
if let firstRoomName = john.residence?[0].name { //通过可选链式调用访问数组下标
print("The first room name is \(firstRoomName).")
} else {
print("Unable to retrieve the first room name.")
}
// 打印 “Unable to retrieve the first room name.”
if let firstRoomName = john.residence?[0].name {
print("The first room name is \(firstRoomName).")
} else {
print("Unable to retrieve the first room name.")
}
// 打印 “Unable to retrieve the first room name.”
john.residence?[0] = Room(name: "Bathroom")
if let johnsStreet = john.residence?.address?.street { //连接多层可选链式调用
print("John's street name is \(johnsStreet).")
} else {
print("Unable to retrieve the address.")
}
// 打印 “Unable to retrieve the address.”
var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]]
testScores["Dave"]?[0] = 91
testScores["Bev"]?[0]++
testScores["Brian"]?[0] = 72 //testScores字典中没有"Brian"这个键,所以第三个调用失败。
// "Dave" 数组现在是 [91, 82, 84],"Bev" 数组现在是 [80, 94, 81]
if let buildingIdentifier = john.residence?.address?.buildingIdentifier() {
print("John's building identifier is \(buildingIdentifier).")
}
// 打印 “John's building identifier is The Larches.”
if let beginsWithThe =
john.residence?.address?.buildingIdentifier()?.hasPrefix("The") { //在方法的可选返回值上进行可选链式调用,在方法的圆括号后面加上问号
if beginsWithThe {
print("John's building identifier begins with \"The\".")
} else {
print("John's building identifier does not begin with \"The\".")
}
}
// 打印 “John's building identifier begins with "The".”
swift学习笔记之-可选链式调用的更多相关文章
- swift 学习- 19 -- 可选链式调用
// 可选链式调用 是一种在当前值可能为 nil 的可选值上请求 和 调用属性, 方法以及下标, 如果 可选值有值, 那么调用就会成功, 如果可选值是 nil, 那么就会将返回 nil , // 多个 ...
- javascript学习(10)——[知识储备]链式调用
上次我们简单的说了下单例的用法,这个也是在我们java中比较常见的设计模式. 今天简单说下链式调用,可能有很多人并没有听过链式调用,但是其实只要我简单的说下的话,你肯定基本上都在用,大家熟知的jQue ...
- 【Swift学习】Swift编程之旅---可选链(二十一)
可选链Optional Chaining是一种可以在当前值可能为nil的可选值上请求和调用属性.方法及下标的方法.如果可选值有值,那么调用就会成功:如果可选值是nil,那么调用将返回nil.多个调用可 ...
- swift学习笔记5——其它部分(自动引用计数、错误处理、泛型...)
之前学习swift时的个人笔记,根据github:the-swift-programming-language-in-chinese学习.总结,将重要的内容提取,加以理解后整理为学习笔记,方便以后查询 ...
- Swift 学习笔记(五)
126. 协议(Protocols) 协议语法(Protocol Syntax) 属性要求(Property Requirements) 方法要求(Method Requirements) Mutat ...
- Swift 学习笔记(四)
116.使用可选链式调用代替强制展开 通过在想调用的属性.方法.或下标的可选值(optional value)后面放一个问号(?),可以定义一个可选链.这一点很像在可选值后面放一个叹号(!)来强制展开 ...
- 《javascript设计模式》笔记之第六章:方法的链式调用
这一章要实现的就是jQuery的那种链式调用,例子: $(this).setStyle('color', 'green').show(); 一:调用链的结构: 首先我们来看一下最简单的$()函数的实现 ...
- Swift2.1 语法指南——可空链式调用
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- JavaScript中的链式调用
链模式 链模式是一种链式调用的方式,准确来说不属于通常定义的设计模式范畴,但链式调用是一种非常有用的代码构建技巧. 描述 链式调用在JavaScript语言中很常见,如jQuery.Promise等, ...
随机推荐
- Azure ARM (11) ARM模式下,创建虚拟机并配置负载均衡器
<Windows Azure Platform 系列文章目录> 本文内容比较多,请大家仔细阅读,谢谢! 在前几章中,我们做了准备工作: 1.创建ARM Resouce Group,叫Lei ...
- resin4 发布war包
1.将web项目打包成xxxx.war 2.将war包放到webapps下 3.修改conf/resin.xml文件如下部分: <!-- - Configures the main applic ...
- [Server] 搭建发布环境Web Deploy
在Web Deploy前,实际上完全可以使用FTP方式发布网站. 如果你购买的只是虚拟空间,那FTP方式更广泛. 先来搭建一套FTP吧 添加FTP服务 在网站上添加FTP发布 配置FTP服务 FTP注 ...
- [译]学习IPython进行交互式计算和数据可视化(二)
第一章:开始使用IPython 在本章中,我们首先进行一遍IPython的安装过程,在大概浏览一下IPython提供的功能.IPython提供了一个高度优化的Python控制台和Notebook.除此 ...
- Node.js系列基础学习----安装,实现Hello World, REPL
Node.js基础学习 简介 简单的说 Node.js 就是运行在服务端的 JavaScript.Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台.Node.js是一 ...
- C#基础04
介绍:泛型介绍,索引,Foreach遍历的解释,yield方法,path文件操作,Directory类基本操作<目录> 一:泛型 百度资料:泛型是 2.0 版 C# 语言和公共语言运行 ...
- TRichTextBox – A universal RichTextBox which can display animated images and more
TRichTextBox – A universal RichTextBox which can display animated images and more trestan, 7 Dec 201 ...
- IStream 接口
IStream 接口 https://msdn.microsoft.com/en-us/library/windows/apps/aa380034 IStream接口允许您读取和写入 stream ...
- WebForm 基础
IIS安装 webForm需要IIS安装 1.安装:控制面板--程序或功能--打开或关闭windows功能--Internet信息服务(打上勾)--确定 2.让vs和IIS相互认识vs:vs2012- ...
- 如何改变 FMX ListView 颜色
需求:改变 ListView 颜色 适用:Firemonkey 任何平台 操作:Style 是改变控件外观最便捷的途径,ListView 也不例外,下面示范使用 StyleBook 来设定 ListV ...