Swift,閉包

kimingw發表於2017-09-14

閉包(相當於匿名函式)的幾種情況

利用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"]

  

相關文章