zoukankan      html  css  js  c++  java
  • 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)

    提高技能如同提升自信心。
  • 相关阅读:
    231. Power of Two
    204. Count Primes
    205. Isomorphic Strings
    203. Remove Linked List Elements
    179. Largest Number
    922. Sort Array By Parity II
    350. Intersection of Two Arrays II
    242. Valid Anagram
    164. Maximum Gap
    147. Insertion Sort List
  • 原文地址:https://www.cnblogs.com/chims-liu-touch/p/9224297.html
Copyright © 2011-2022 走看看