swift之闭包
func test(_ message: String,completion:(_ goodbye: String) ->Void){
print(message)
completion("Goodbye")
}
typealias omit = (_ goodbye: String) ->Void
/// 1.一般形式
test("closures", completion: {(_ goodbye: String) ->Void in
print(goodbye)
})
/// 2.尾随闭包 省略参数名
test("message") {(_ goodbye: String) ->Void in
print(goodbye)
}
/// 3.别名形式 比较适合无参形式 毕竟闭包中的参数都是需要引用的
test("omit") { omit in
}
/// 4.闭包参数简写 使用$0,$1表示闭包中的第一个参数,第二个参数
test("omit") {
print($0)
}
//// 使用循环
let values = [1,3,5,7]
var results = [Int]()
for var value in values {
value *= 2
results.append(value)
}
print(results)
//// 用闭包解包
let results11 = values.map() { $0*2
}
print("printf=\(results11)")
/// 去空值
let name:[Int?] = [1,3,5,7,9,nil]
let flattenResult = name.compactMap{ $0 }
print(flattenResult)
/// 压平
let values1 = [[1,3,5,7,59,41],[9]]
let flattenResult1 = values1.flatMap{ $0 }
////排序
let flattenResult2 = flattenResult1.sorted(by: { $1 > $0 })
print(flattenResult2)