func test(_ message: String,completion:(_ goodbye: String) ->Void){閉包
print(message)app
completion("Goodbye")排序
}it
typealias omit = (_ goodbye: String) ->Voidio
/// 1.通常形式test
test("closures", completion: {(_ goodbye: String) ->Void in循環
print(goodbye)map
})引用
/// 2.尾隨閉包 省略參數名closure
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)