首页 > 代码库 > Swift_4_闭包(Blocks)
Swift_4_闭包(Blocks)
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 //}
Swift_4_闭包(Blocks)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。