//: Playground - noun: a place where people can play
import UIKit
var title = "Swift 闭包表达式-来自CocoaChina"
var describe = "1,利用上下文推断参数和返回值类型;2,单表达式闭包可以省略return关键字;3,参数名称简写;4,Trailing闭包语法"
//1,字母逆序排序
let names = ["China","Alex","Barrt","Ewa","Cocoa","Eye"]
//系统提供sort函数:排序两个参数:a,已经类型的数组;b,排序闭包 (String,String) -> Bool
func backWards(s1:String,s2:String) -> Bool
{
return s1 > s2
}
var first = "第一种排序方式:排序函数"
var firstReversed = names.sorted(by:backWards)
/*
闭包表达式的形式
{(parameters) -> returnType in
statements
}
*/
var second = "第二种排序方式:排序内联闭包"
var secondReversed = names.sorted { (s1:String, s2:String) -> Bool in
return s1 > s2
}
// in 表示闭包的参数和返回值类型定义已经完成,闭包函数体即将开始
//根据上下文推断类型
var secondReversedA = names.sorted()
var secondReversedB = names.sorted { (s1, s2) -> Bool in
return s1 > s2
}
var third = "第三种排序方式:运算符函数"
var thirdReversed = names.sorted(by: >)
var trailing = "Trailing闭包"
var trailingDescribe = "如果是一个很长的闭包表达式作为最后一个参数传递给函数,可以使用trailing闭包增强函数的可读性"
var map = "map方法的使用"
//将Int类型的数组转化为对应的字符串类型的数组
let digitnames = [0:"零",1:"一",2:"二",3:"三",4:"四",5:"五",6:"六",7:"七",8:"八",9:"九"]
let numbers = [14,305,9,94]
let strings = numbers.map { ( num) -> String in
var str = ""
var currentNum = num
while currentNum > 0 {
str = digitnames[(currentNum%10)]! + str
currentNum = currentNum/10
}
return str
}
// ! 代表 force-unwrap
var caputure = "捕获Caputure"
var caputureDescribe = "闭包可以在其定义的上下文中捕获常量或变量。即使定义这些常量和变量的作用域已经不存在了,闭包仍然可以在闭包函数体内引用和修改这些值"