Skip to content

Instantly share code, notes, and snippets.

@safecat
Created July 7, 2015 02:01
Show Gist options
  • Save safecat/5d7b33ca8d7c7891e92d to your computer and use it in GitHub Desktop.
Save safecat/5d7b33ca8d7c7891e92d to your computer and use it in GitHub Desktop.
Swift 闭包学习
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
// 普通函数
func desc(s1 : String, s2 : String) -> Bool {
return s1 > s2
}
names.sort(desc)
// 闭包
names.sort({(s1 : String, s2 : String) -> Bool in
return s1 < s2
})
// 上下文闭包(根据上下文推断函数类型)
names.sort({s1, s2 in
return s1 > s2
})
// 单行闭包隐式返回
var reversed = names.sort({s1, s2 in s1 < s2})
reversed
// 参数名称缩写
reversed = names.sort({ $0 > $1 })
reversed
// 运算符函数
names.sort(<)
// 尾随闭包
reversed = names.sort(){$0>$1}
reversed
// 定义一个以闭包作为参数的函数
func customsort(items : [String], callback : () -> ()){
}
// 上下文捕获
func aaa() {
var a = 1
func bbb() {
a = 2
}
bbb()
print(a, appendNewline: false)
}
aaa()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment