你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> Swift_閉包

Swift_閉包

編輯:IOS開發綜合

此文描述了Swift_閉包的相關介紹,具體代碼請看下文

Swift_閉包

點擊查看源碼

閉包優化
//閉包優化
func testClosures() {
    //函數做參數 排序
    let names = ["XuBaoAiChiYu", "1045214799", "IOS", "Swift", "OC"]
    func backwards(_ s1: String, _ s2: String) -> Bool {
        return s1 > s2
    }
    var reversed = names.sorted(by: backwards)
    print(reversed)
    
    //閉包排序
    reversed = names.sorted(by: { (s1: String, s2: String) -> Bool in
        return s1 > s2
    })
    print(reversed)
    
    //可以寫為一行
    reversed = names.sorted( by: { (s1: String, s2: String) -> Bool in return s1 > s2 } )
    print(reversed)
    
    //閉包可以自動判斷參數類型和返回屬性
    reversed = names.sorted( by: { s1, s2 in return s1 > s2 } )
    print(reversed)
    
    //當只有一行時,可省略return寫法。
    reversed = names.sorted( by: { s1, s2 in s1 > s2 } )
    print(reversed)
    
    //閉包中的參數可使用$去獲得 第一個參數為$0 第二個為$1
    reversed = names.sorted( by: { $0 > $1 } )
    print(reversed)
    
    //當閉包中只有兩個參數 做比較操作時 只需要寫入符號
    reversed = names.sorted(by: >)
    print("\(reversed)")
    
    /*  print
     
     ["IOS", "XuBaoAiChiYu", "Swift", "OC", "1045214799"]
     ["IOS", "XuBaoAiChiYu", "Swift", "OC", "1045214799"]
     ["iOS", "XuBaoAiChiYu", "Swift", "OC", "1045214799"]
     ["iOS", "XuBaoAiChiYu", "Swift", "OC", "1045214799"]
     ["iOS", "XuBaoAiChiYu", "Swift", "OC", "1045214799"]
     ["iOS", "XuBaoAiChiYu", "Swift", "OC", "1045214799"]
     ["iOS", "XuBaoAiChiYu", "Swift", "OC", "1045214799"]
     
     */
}
尾隨閉包
//尾隨閉包
func testTrailingClosures() {
    
    let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
    
    //如果函數需要一個閉包作為參數,且這個參數是最後一個參數.
    //尾隨閉包可以放在函數參數列表外,也就是括號外
    var reversed = names.sorted() { $0 > $1 }
    print("\(reversed)")
    
    //如果一個閉包表達式作為一個唯一的參數,你又正在使用尾隨閉包,可以省略()
    reversed = names.sorted { $0 > $1 }
    print("\(reversed)")
    
    /*  print
     
     ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
     ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
     
     */
}
捕獲值
//捕獲值
func testCapturingValues() {
    /*
     閉包可以根據環境上下文捕獲到定義的常量和變量。閉包可以引用和修改這些捕獲到的常量和變量,
     就算在原來的范圍內定義為常量或者變量已經不再存在(很牛逼)。
     在Swift中閉包的最簡單形式是嵌套函數。
     */
    func makeIncrementer(forIncrement amount: Int) -> () -> Int {
        var runningTotal = 0
        func incrementer() -> Int {
            runningTotal += amount
            return runningTotal
        }
        return incrementer
    }
    
    let incrementByTen = makeIncrementer(forIncrement: 10)
    print("\(incrementByTen())")
    print("\(incrementByTen())")
    print("\(incrementByTen())")
    
    let incrementBySeven = makeIncrementer(forIncrement: 7)
    print("\(incrementBySeven())")
    print("\(incrementByTen())")
    
    //閉包是引用類型
    let alsoIncrementByTen = incrementByTen
    print(alsoIncrementByTen())
    
    /*  print
     
     10
     20
     30
     7
     40
     50
     
     */
}
避免內存洩露
//避免內存洩露
var completionHandlers: [() -> Void] = []
func someFunctionWithNoescapeClosure(_ closure: () -> Void) {
    closure()
//    completionHandlers.append(closure) //會報錯 closure無法被保存
}

func someFunctionWithEscapingClosure(_ completionHandler: @escaping () -> Void) {
    completionHandler()
    completionHandlers.append(completionHandler)
}

class SomeClass {
    var x = 10
    func Dosomething() {
        //內存溢出
        someFunctionWithEscapingClosure { self.x = 100 }
        someFunctionWithNoescapeClosure { x = 200 }
    }
}
func testNonescapingClosures() {
    //@noescape 保留環問題 閉包中布應使用self 避免內存洩露
    let instance = SomeClass()
    instance.Dosomething()
    print(instance.x)
    
    completionHandlers.first?()
    print(instance.x)
    
    /*  print
     
     200
     100
     
     */
}



通本學習您是不是更了解ios開發了呢.感謝關注本站

【Swift_閉包】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved