swift @AUTOCLOSURE 和 ?? ||
* {-webkit-tap-highlight-color: rgba(0,0,0,0);}html {-webkit-text-size-adjust: none;}body {font-family: Arial, Helvetica, sans-serif;margin: 0;color: #333;word-wrap: break-word;}h1, h2, h3, h4, h5, h6 {line-height: 1.1;}img {max-width: 100% !important;}blockquote {margin: 0;padding: 0 15px;color: #777;border-left: 4px solid #ddd;}hr {background-color: #ddd;border: 0;height: 1px;margin: 15px 0;}code {font-family: Menlo, Consolas, 'Ubuntu Mono', Monaco, 'source-code-pro', monospace;line-height: 1.4;margin: 0;padding: 0.2em 0;font-size: 85%;background-color: rgba(0,0,0,0.04);border-radius: 3px;}pre > code {margin: 0;padding: 0;font-size: 100%;word-break: normal;background: transparent;border: 0;}ol {list-style-type: decimal;}ol ol, ul ol {list-style-type: lower-latin;}ol ol ol, ul ol ol, ul ul ol, ol ul ol {list-style-type: lower-roman;}table {border-spacing: 0;border-collapse: collapse;margin-top: 0;margin-bottom: 16px;}table th {font-weight: bold;}table th, table td {padding: 6px 13px;border: 1px solid #ddd;}table tr {border-top: 1px solid #ccc;}table tr:nth-child(even) {background-color: #f8f8f8;}input[type="checkbox"] {cursor: default;margin-right: 0.5em;font-size: 13px;}.task-list-item {list-style-type: none;}.task-list-item+.task-list-item {margin-top: 3px;}.task-list-item input {float: left;margin: 0.3em 1em 0.25em -1.6em;vertical-align: middle;}#tag-field {margin: 8px 2px 10px;}#tag-field .tag {display: inline-block;background: #cadff3;border-radius: 4px;padding: 1px 8px;color: black;font-size: 12px;margin-right: 10px;line-height: 1.4;}
.ace_static_highlight {white-space: pre-wrap;}.ace_static_highlight .ace_gutter {width: 2em;text-align: right;padding: 0 3px 0 0;margin-right: 3px;}.ace_static_highlight.ace_show_gutter .ace_line {padding-left: 2.6em;}.ace_static_highlight .ace_line {position: relative;}.ace_static_highlight .ace_gutter-cell {-moz-user-select: -moz-none;-khtml-user-select: none;-webkit-user-select: none;user-select: none;top: 0;bottom: 0;left: 0;position: absolute;}.ace_static_highlight .ace_gutter-cell:before {content: counter(ace_line, decimal);counter-increment: ace_line;}.ace_static_highlight {counter-reset: ace_line;}
.ace-chrome .ace_gutter {background: #ebebeb;color: #333;overflow : hidden;}.ace-chrome .ace_print-margin {width: 1px;background: #e8e8e8;}.ace-chrome {background-color: #FFFFFF;color: black;}.ace-chrome .ace_cursor {color: black;}.ace-chrome .ace_invisible {color: rgb(191, 191, 191);}.ace-chrome .ace_constant.ace_buildin {color: rgb(88, 72, 246);}.ace-chrome .ace_constant.ace_language {color: rgb(88, 92, 246);}.ace-chrome .ace_constant.ace_library {color: rgb(6, 150, 14);}.ace-chrome .ace_invalid {background-color: rgb(153, 0, 0);color: white;}.ace-chrome .ace_fold {}.ace-chrome .ace_support.ace_function {color: rgb(60, 76, 114);}.ace-chrome .ace_support.ace_constant {color: rgb(6, 150, 14);}.ace-chrome .ace_support.ace_type,.ace-chrome .ace_support.ace_class.ace-chrome .ace_support.ace_other {color: rgb(109, 121, 222);}.ace-chrome .ace_variable.ace_parameter {font-style:italic;color:#FD971F;}.ace-chrome .ace_keyword.ace_operator {color: rgb(104, 118, 135);}.ace-chrome .ace_comment {color: #236e24;}.ace-chrome .ace_comment.ace_doc {color: #236e24;}.ace-chrome .ace_comment.ace_doc.ace_tag {color: #236e24;}.ace-chrome .ace_constant.ace_numeric {color: rgb(0, 0, 205);}.ace-chrome .ace_variable {color: rgb(49, 132, 149);}.ace-chrome .ace_xml-pe {color: rgb(104, 104, 91);}.ace-chrome .ace_entity.ace_name.ace_function {color: #0000A2;}.ace-chrome .ace_heading {color: rgb(12, 7, 255);}.ace-chrome .ace_list {color:rgb(185, 6, 144);}.ace-chrome .ace_marker-layer .ace_selection {background: rgb(181, 213, 255);}.ace-chrome .ace_marker-layer .ace_step {background: rgb(252, 255, 0);}.ace-chrome .ace_marker-layer .ace_stack {background: rgb(164, 229, 101);}.ace-chrome .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid rgb(192, 192, 192);}.ace-chrome .ace_marker-layer .ace_active-line {background: rgba(0, 0, 0, 0.07);}.ace-chrome .ace_gutter-active-line {background-color : #dcdcdc;}.ace-chrome .ace_marker-layer .ace_selected-word {background: rgb(250, 250, 255);border: 1px solid rgb(200, 200, 250);}.ace-chrome .ace_storage,.ace-chrome .ace_keyword,.ace-chrome .ace_meta.ace_tag {color: rgb(147, 15, 128);}.ace-chrome .ace_string.ace_regex {color: rgb(255, 0, 0)}.ace-chrome .ace_string {color: #1A1AA6;}.ace-chrome .ace_entity.ace_other.ace_attribute-name {color: #994409;}.ace-chrome .ace_indent-guide {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==") right repeat-y;}
body{margin:0 auto;max-width:800px;line-height:1.4}
#nav{margin:5px 0 10px;font-size:15px}
#titlearea{border-bottom:1px solid #ccc;font-size:17px;padding:10px 0;}
#contentarea{font-size:15px;margin:16px 0}
.cell{outline:0;min-height:20px;margin:5px 0;padding:5px 0;}
.code-cell{font-family:Menlo,Consolas,'Ubuntu Mono',Monaco,'source-code-pro',monospace;font-size:12px;}
.latex-cell{white-space:pre-wrap;}
.text-cell {font-size: 15px;}.code-cell {font-size: 12px;}.markdown-cell {font-size: 15px;}.latex-cell {font-size: 15px;}
swift @AUTOCLOSURE 和 ?? ||
@AUTOCLOSURE 和 ??
由 王巍 (@ONEVCAT) 发布于 2014-08-20
Apple 为了推广和介绍 Swift,破天荒地为这门语言开设了一个博客(当然我觉着是因为 Swift 坑太多需要一个地方来集中解释)。其中有一篇提到了一个叫做 @autoclosure
的关键词。
@autoclosure
可以说是 Apple 的一个非常神奇的创造,因为这更多地是像在 “hack” 这门语言。简单说,@autoclosure
做的事情就是把一句表达式自动地封装成一个闭包 (closure)。这样有时候在语法上看起来就会非常漂亮。
比如我们有一个方法接受一个闭包,当闭包执行的结果为 true
的时候进行打印:
func logIfTrue(predicate: () -> Bool) {
if predicate() {
print("True")
}
}
在调用的时候,我们需要写这样的代码
logIfTrue({return 2 > 1})
当然,在 Swift 中对闭包的用法可以进行一些简化,在这种情况下我们可以省略掉 return
,写成:
logIfTrue({2 > 1})
还可以更近一步,因为这个闭包是最后一个参数,所以可以使用尾随闭包 (trailing closure) 的方式把大括号拿出来,然后省略括号,变成:
logIfTrue{2 > 1}
但是不管哪种方式,要么是书写起来十分麻烦,要么是表达上不太清晰,看起来都让人生气。于是 @autoclosure
登场了。我们可以改换方法参数,在参数名前面加上 @autoclosure
关键字:
func logIfTrue(@autoclosure predicate: () -> Bool) {
if predicate() {
print("True")
}
}
这时候我们就可以直接写:
logIfTrue(2 > 1)
来进行调用了,Swift 将会把 2 > 1
这个表达式自动转换为 () -> Bool
。这样我们就得到了一个写法简单,表意清楚的式子。
在 Swift 中,有一个非常有用的操作符,可以用来快速地对 nil
进行条件判断,那就是 ??
。这个操作符可以判断输入并在当左侧的值是非 nil
的 Optional 值时返回其 value,当左侧是 nil
时返回右侧的值,比如:
var level : Int?
var startLevel = 1
var currentLevel = level ?? startLevel
在这个例子中我们没有设置过 level
,因此最后 startLevel
被赋值给了 currentLevel
。如果我们充满好奇心地点进 ??
的定义,可以看到 ??
有两种版本:
func ??<T>(optional: T?, @autoclosure defaultValue: () -> T?) -> T?
func ??<T>(optional: T?, @autoclosure defaultValue: () -> T) -> T
在这里我们的输入满足的是后者,虽然表面上看 startLevel
只是一个 Int
,但是其实在使用时它被自动封装成了一个 () -> Int
,有了这个提示,我们不妨来猜测一下 ??
的实现吧:
func ??<T>(optional: T?, @autoclosure defaultValue: () -> T) -> T {
switch optional {
case .Some(let value):
return value
case .None:
return defaultValue()
}
}
可能你会有疑问,为什么这里要使用 autoclosure
,直接接受 T
作为参数并返回不行么,为何要用 () -> T
这样的形式包装一遍,岂不是画蛇添足?其实这正是 autoclosure
的一个最值得称赞的地方。如果我们直接使用 T
,那么就意味着在 ??
操作符真正取值之前,我们就必须准备好一个默认值传入到这个方法中,一般来说这不会有很大问题,但是如果这个默认值是通过一系列复杂计算得到的话,可能会成为浪费 -- 因为其实如果 optional
不是 nil
的话,我们实际上是完全没有用到这个默认值,而会直接返回 optional
解包后的值的。这样的开销是完全可以避免的,方法就是将默认值的计算推迟到 optional
判定为 nil
之后。
就这样,我们可以巧妙地绕过条件判断和强制转换,以很优雅的写法处理对 Optional
及默认值的取值了。最后要提一句的是,@autoclosure
并不支持带有输入参数的写法,也就是说只有形如 () -> T
的参数才能使用这个特性进行简化。另外因为调用者往往很容易忽视 @autoclosure
这个特性,所以在写接受 @autoclosure
的方法时还请特别小心,如果在容易产生歧义或者误解的时候,还是使用完整的闭包写法会比较好。
练习
在 Swift 中,其实
&&
和||
这两个操作符里也用到了@autoclosure
。作为练习,不妨打开 Playground,试试看怎么实现这两个操作符吧?
Swift 的 autoclosure
Swift 的 autoclosure
在 Swift 中,如果一个函数,接收一个 closure 作为参数,我们可以这么写:
func op() -> Int {
return 8
} func function(a: () -> Int) {
print(a())
} //调用
function{ op() } //打印8
如果这个参数使用 autoclosure 修饰,则可以这么写:
func op() -> Int {
return 8
} func function(@autoclosure a: () -> Int) {
print(a())
} //调用
function(op()) //打印8
Swift 会将该参数自动包到 closure 里传给函数。那么除了语法区别,还有什么作用呢?
一个很好的例子就是 swift 自带的 ?? 操作符,这个操作符很简单,如果让我们自己实现,第一想到的就是这样写:
infix operator ??? {associativity right precedence 110} func ???<T>(opt: T?, defaultVal: T) -> T {
if let x = opt {
return x
} else {
return defaultVal
}
} let opt: Int? = 1
let nilopt: Int? = nil
let a: Int = opt ??? 10
let b: Int = nilopt ??? 10
print(a) //打印1
print(b) //打印10
看起来不错,但是其实有个问题,假如我们的 defaultVal 传的是一个返回 Int 的函数,那么即使 opt 不是 nil,defaultVal 值不会被用到,这个函数也会被执行:
func op() -> Int {
print("run")
return 8
} let opt: Int? = 1
let a: Int = opt ??? op()
print(a)
//打印 run\n 1
这里 op 函数的执行是没有必要的,因为 opt 是有值的,op 函数的结果不会被用到,这里做了一次额外不用的运算,如果 op 函数的性能开销很大,对整个 app 的性能是有影响的。
解决方法就是把 defaultVal 作为一个 closure,这样只有在 opt 为 nil 时,才会去执行 closure 里的代码
func op() -> Int {
print("run")
return 8
} infix operator ??? {associativity right precedence 110} func ???<T>(opt: T?, defaultVal: () -> T) -> T {
if let x = opt {
return x
} else {
return defaultVal()
}
} let opt: Int? = 1
let a: Int = opt ??? {op()}
print(a)
//打印 1
看到那奇怪的中括号了么,因为我们 defaultVal 参数接受的是一个 closure,参数打上大括号作为一个 closure 传入。
这显然是不太能接受的语法。所以我们需要 autoclosure,把参数自动包成 closure。
func op() -> Int {
print("run")
return 8
} infix operator ??? {associativity right precedence 110} func ???<T>(opt: T?, @autoclosure defaultVal: () -> T) -> T {
if let x = opt {
return x
} else {
return defaultVal()
}
} let opt: Int? = 1
let a: Int = opt ??? op()
print(a)
//打印 1
swift @AUTOCLOSURE 和 ?? ||的更多相关文章
- Swift开发第五篇——四个知识点(Struct Mutable方法&Tuple&autoclosure&Optional Chain)
本篇分三部分: 一.Struct Mutable方法 二.多元组(Tuple) 的使用 三.autoclosure 的使用 四.Optional Chain 的使用 一.Struct Mutable方 ...
- Swift闭包(I) @autoclosure和@escaping的区别
1. 参考资料 https://www.cnblogs.com/sgxx/p/6209944.html https://www.jianshu.com/p/99ade4feb8c1
- iOS8.3发布了Swift 1.2带来哪些新变化
苹果前几日在面向开发者推送iOS 8.3 Beta的同时,还发布了版本号为6D520o的Xcode 6.3 Beta,其中便包含了iOS 8.3 Beta和OS X v10.10 SDK,并进一步提升 ...
- IOS系列swift语言之课时三
今天需要掌握的内容就是:闭包.类.结构体.属性(计算属性和延迟属性) 同样里面有一些题目,有兴趣的可以做一下. 首先我们需要知道什么是闭包?所谓的闭包就是一个代码块(一般是指函数以及被它捕获的成员变量 ...
- swift 学习(一)基础知识 (基本数据类型,操作符,流控制,集合)
xcode 中调用API帮助 1.查看简单信息,选中后 按键 control +左键单击 或者按 右侧属性栏 里的帮助按钮 2.完整API,选中后 按键 control +左键双击 3.查看类.函数 ...
- swift学习笔记之-闭包
//闭包 import UIKit /*闭包(Closures): 函数.闭包.类都是引用类型(引用类型的实例赋值给变量或常量时,得到的都是该实例的引用,而值类型的实例变量得到的是独立的值的拷贝) 1 ...
- Swift开发第一篇——异常处理及断言
本篇分两部分: 1.错误和异常处理 2.Swift 中的断言 1.错误和异常处理 在 OC 开发中,我们通常会将 error 置为 nil NSError *error; BOOL success = ...
- iOS - Swift 基本语法
前言 Swift 全面支持 Unicode 符号. Swift 中的定义和实现是在同一个单元中的,通常一个 Swift 源代码单文件是以 ".Swift" 结尾的. Swift 不 ...
- 一起聊聊 Swift 3.0
Swift3.0将会给我们带来哪些改变: 1. 稳定二进制接口(ABI) ABI是什么呢?API大家都知道是应用程序接口 API只是提供函数签名 而ABI是系统和语言层面的 如果ABI稳定 意味着以后 ...
随机推荐
- Config程序配置文件操作实践进阶之ConfigurationSectionGroup
今天又进一步对System.Configuration下的ConfigurationSectionGroup类及相关的类与方法进行了研究.发现要构建多层次嵌套的XML标签 则必须用到Configura ...
- 专注做好一件事(转) focus---这个世界上最成功的人,他们在某一领域获得成功之后,可通过经营杠杆进入任何他们想要涉足的领域。而这都得依赖于他们曾极致的专注在做好一件事情上。
- 批量 1 insert into select 2 sqldataadapter.update 3 SELECT INTO FROM (要求目标表不存在) 4 AddRange(ef) 5 MySqlBulkLoader.Load() 6 BatchInsert 7 insert bulk
insert into a(col1,col2) select top 1 '1','2' from a union select top 1 '3','4' from a SELECT IN ...
- Linux中断的系统调用
早期UNIX系统的一个特性是:如果在进程执行一个低速系统调用而阻塞期间捕捉到一个信号,则该系统调用就被中断不再继续执行.该系统调用返回出错,其errno设置为EINTR.这样处理的理由是:因为一个信号 ...
- 用GDI+DrawImage画上去的图片会变大
问题: 用GDI+DrawImage画上去的图片会变大 解释: Status DrawImage(Image *image,const Point &point);两参数的这个接口是这么设计的 ...
- 64位FreeSWITCH编译安装(版本1.4.20)
1.安装64位的CentOS6.5操作系统(勾选的服务器版本安装). 2.下载FreeSWITCH安装包以及关联的lib库.下载地址http://files.freeswitch.org/downlo ...
- 基于 Transaction 类的分布式显式事务
自.NET2.0以来增加了System.Transactions命名空间,为.NET应用程序带来了一个新的事务编程模型. 这个命名空间提供了几个依赖的TransactionXXX类.Transacti ...
- java字符串拼接的几种方式
1. plus方式 当左右两个量其中有一个为String类型时,用plus方式可将两个量转成字符串并拼接. String a="";int b=0xb;String c=a+b;2 ...
- 常用代码之四:创建jason,jason转换为字符串,字符串转换回jason,c#反序列化jason字符串的几个代码片段
1.创建jason,并JSON.stringify()将之转换为字符串. 直接使用var customer={}, 然后直接customer.属性就可以直接赋值了. 也可以var customer = ...
- java.lang.RuntimeException: Date pattern must be set for column update_time in the schema of component
使用Talend open studio ,从mysql数据源中读取数据,将数据导出到excel文档,另外一个mysql数据库,和一个普通文件,遇到标题的错误,模型如下图所示: tMap将30.7中 ...