Swift,闭包

闭包(相当于匿名函数)的几种情况

利用sorted()排序方法来进行示例

1、sorted()正常引用的情况

var str=["d","a","c","b"]
var sort=str.sorted()  //["a", "b", "c", "d"]

2、设置函数导致sorted()倒序

var str=["d","a","c","b"]
func sortdown(a:String,b:String)->Bool{
  return	a>b
}
var sort1=str.sorted(by:sortdown)  //["d", "c", "b", "a"]

3、闭包进行改写

(1)最正常的改写

var str=["d","a","c","b"]
var sort1=str.sorted{(a:String,b:String)->Bool in  //["d","c","b","a"]
  return a>b
}

(2)利用函数自动推断,参数和返回值都可以自动推断,return也可以省略

var str=["d","a","c","b"]
var sort1=str.sorted{(a,b)in
  a>b  //["d","c","b","a"]
}

(3)利用快捷参数直接引用

var str=["d","a","c","b"]
var sort1=str.sorted{$0>$1}  //["d","c","b","a"]

  

posted @ 2017-09-14 11:01  kimingw  阅读(120)  评论(0编辑  收藏  举报