Swift4 基础部分:Closures

本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

系列文章:

Closures

闭包表达式语法(Closure Expression Syntax)

Closure expression syntax has the following general form:

 { (parameters) -> return type in
    statements
}

例子:数组排序的例子

var names:[String] = ["B","A","C"];
names = names.sorted(by: {
    (num1:String,num2:String) -> Bool in
    return num1 < num2;
});
print(names);

执行结果:

["A", "B", "C"]

上下文检测类型(Inferring Type From Context)

Because the sorting closure is passed as an argument to a 
method, Swift can infer the types of its parameters and 
the type of the value it returns. The sorted(by:) method 
is being called on an array of strings, so its argument 
must be a function of type (String, String) -> Bool. This 
means that the (String, String) and Bool types do not need 
to be written as part of the closure expression’s 
definition.
  • 排序的闭包因为Swift中的类型检测机制,所以可以省掉写入String,-> Bool

针对上述的例子做简化:

var names:[String] = ["B","A","C"];
names = names.sorted(by: {
    (name1,name2) in
    return name1 < name2;
});
print(names);

单表达式闭包的隐式返回(Implicit Returns from Single-Expression Closures)

Single-expression closures can implicitly return the 
result of their single expression by omitting the return 
keyword from their declaration
  • 单表达式的闭包可以省略掉return关键字

继续简化上述例子:

var names:[String] = ["B","A","C"];
names = names.sorted(by: {
    (name1,name2) in name1 < name2;
});
print(names);

参数名称缩写(Shorthand Argument Names)

Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.
  • 结合闭包中类型的检测,闭包中的参数名可以使用$0, $1, $2代替

继续简化上述例子:

var names:[String] = ["B","A","C"];
names = names.sorted(by: {
    $0 < $1;
});
print(names);

操作方法(Operator Methods)

There’s actually an even shorter way to write the closure 
expression above. Swift’s String type defines its string-
specific implementation of the greater-than operator (>) 
as a method that has two parameters of type String, and 
returns a value of type Bool.
  • 继续简化可以直接用>,<表示比较结果

继续简化例子:

var names:[String] = ["B","A","C"];
names = names.sorted(by:<);
print(names);

尾随闭包(Trailing Closures)

If you need to pass a closure expression to a function as 
the function’s final argument and the closure expression 
is long, it can be useful to write it as a trailing 
closure instead. A trailing closure is written after the 
function call’s parentheses, even though it is still an 
argument to the function. When you use the trailing 
closure syntax, you don’t write the argument label for the 
closure as part of the function call.
  • 当闭包是函数中的最后一个参数时,函数调用可以省略掉参数标签的写法,简化函数

闭包是引用类型数据(Closures Are Reference Types)

In the example above, incrementBySeven and incrementByTen 
are constants, but the closures these constants refer to 
are still able to increment the runningTotal variables 
that they have captured. This is because functions and 
closures are reference types.
  • Swift中的闭包是引用类型的数据

例子:

var num = 0;
func increment(completion:() -> Void){
    completion();
    print("num:\(num)");
}
increment {
    num += 10;
}
let referIncrement = increment;
referIncrement{
    num += 20;
}

执行结果:

num:10
num:30

逃逸闭包(Escaping Closures)

A closure is said to escape a function when the closure is 
passed as an argument to the function, but is called after 
the function returns. When you declare a function that 
takes a closure as one of its parameters, you can write 
@escaping before the parameter’s type to indicate that the 
closure is allowed to escape.
  • Swift中如果需要逃逸闭包需要利用关键字@escaping修饰

例子:

var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
    completionHandlers.append(completionHandler)
}

func someFunctionWithNonescapingClosure(closure: () -> Void) {
    closure()
}

class SomeClass {
    var x = 10
    func doSomething() {
        
        someFunctionWithEscapingClosure(completionHandler: {
            self.x = 100;
        });
        
        someFunctionWithNonescapingClosure(closure: {
            x = 200;
        });
        
        // 以下的调用方式一样可行,同时说明了尾随闭包的使用
        //someFunctionWithEscapingClosure { self.x = 100 }
        //someFunctionWithNonescapingClosure { x = 200 }
    }
}
let instance = SomeClass()
instance.doSomething()
print(instance.x)
completionHandlers.first?()
print(instance.x)

执行结果:

200
100

自动闭包(Autoclosures)

An autoclosure is a closure that is automatically created 
to wrap an expression that’s being passed as an argument 
to a function. It doesn’t take any arguments, and when 
it’s called, it returns the value of the expression that’s 
wrapped inside of it.
  • Swift中的自动闭包能动态的封装一个表达式为一个函数的参数,自动闭包不能带任何的参数

例子:


var num = 1;
func filter(contions:() -> Bool){
    if contions(){
        num += 3;
        print("num:\(num)");
    }else{
        num += 1;
        print("num:\(num)");
        filter(contions: {num % 3 == 0})
    }
}
filter(contions: { num % 3 == 0 })

执行结果:

num:2
num:3
num:6

下面开始利用@autoclosure简化:

var num = 1;
func filter(_ contions: @autoclosure () -> Bool){
    if contions(){
        num += 3;
        print("num:\(num)");
    }else{
        num += 1;
        print("num:\(num)");
        filter(num % 3 == 0)
    }
}
filter(num % 3 == 0)
Overusing autoclosures can make your code hard to 
understand. The context and function name should make it 
clear that evaluation is being deferred.
  • autoclosure的过度使用并不好,会让代码逻辑看起来更难理解,必须了解上下文中函数的定义才可结合使用
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容

  • 1.前言: Swift包含了 C 和 Objective-C上所有基础数据类型,Int表示整型值; Double和...
    廖马儿阅读 207评论 0 0
  • 86.复合 Cases 共享相同代码块的多个switch 分支 分支可以合并, 写在分支后用逗号分开。如果任何模式...
    无沣阅读 1,274评论 1 5
  • importUIKit classViewController:UITabBarController{ enumD...
    明哥_Young阅读 3,680评论 1 10
  • 以下翻译自Apple官方文档,结合自己的理解记录下来。翻译基于 swift 3.0.1 原文地址 Closure...
    艺术农阅读 1,429评论 0 3
  • 妈妈带着妞妞来园里玩,妞妞很是兴奋,到处跑来跑去,一会儿钻到海洋球里,一会儿骑到小老虎车上飞快地跑,妈妈跟...
    未央之雨阅读 455评论 0 0