import Foundation println("Hello, World!") var arr = [1,2,4,6,74,2] func hasClosure(list:[Int], v2:Int, cb:(num:Int, v3:Int) ->Bool) ->Bool{ for item in arr{ if(cb(num:item, v3:v2)){ return true; } } return false; } var v2 = hasClosure(arr, 82, { (num:Int, v3:Int) ->Bool in return num >= v3; }); println("v2 is \(v2)") //sort函数 会根据您提供的排序闭包将已知类型数组中的值进行排序。 一旦排序完成,函数会返回一个与原数组大小相同的新数组,该数组中包含已经正确排序的同类型元素 let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] func backwards(s1: String, s2: String) -> Bool { return s1 > s2 } var reversed = sort(names, backwards) // reversed is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"] //闭包版 reversed = sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 }) //单行 reversed = sort(names, { (s1: String, s2: String) -> Bool in return s1 > s2 } ) //再精简 reversed = sort(names, { s1, s2 in s1 > s2 } ) //极致精简 reversed = sort(names, { $0 > $1 } ) //终极精简 reversed = sort(names, >) println("reversed is \(reversed)") //闭包表达式 //{ // (parameters) -> returnType in // statements //}
时间: 2024-11-06 18:27:05