// // ViewController.swift // 閉包的定義和使用 // // Created by 思 彭 on 16/9/17. // Copyright © 2016年 思 彭. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 1>. 最簡單的閉包 ()->()沒有參數,沒有返回值的函數 如果沒有參數,沒有返回值,in可以省略 let b1 = { print("Hello SiSi") } // 執行閉包 b1() // 2. 帶參數的閉包 參數,返回值,實現代碼都是寫在{}中 // {形參列表 - >返回值類型 // 實現代碼} // 使用 in 分割定義和實現 b2的類型: (Int) -> () let b2 = { (x: Int ) ->() in print(x) } // 執行閉包 b2(100) // 3.帶參數/返回值的閉包 // (Int) -> Int let b3 = {(y: Int) ->Int in return y + 250 } // 閉包調用 print(b3(30)) // 4.異步執行任務,獲取數據,通過block/閉包回調,閉包的應用場景和閉包一樣 // 5.尾隨閉包 如果函數的最后一個參數是閉包,函數的參數可以提前結束,最后一個參數直接使用{}包裝閉包的代碼 /* loadData() { (result) in print(result) } */ loadData { (result) in print(result) } // 按照函數的本身編寫 loadData(completion: {(result) -> () in print(result) }) } func demo1() { // 尾隨閉包 DispatchQueue.global().async { // 嵌套的GCD xcode不會改成尾隨閉包 DispatchQueue.main.async(execute: { }) } // 尾隨閉包 DispatchQueue.main.async { } } func loadData(completion: (result: [String]) ->()) -> () { // 將任務添加到隊列,執行任務的操作,隊列的調度是以同步/異步執行任務 DispatchQueue.global().async{ print("耗時操作\(Thread .current())") // 休眠 Thread.sleep(forTimeInterval: 1.0) // 獲得數據 let json = ["頭條","八卦","出大事了"] //主線程更新 DispatchQueue.main.async(execute: { print("主線程更新UI\(Thread.current())") // 回調,執行,通過參數回調 completion(result: json) }) } } // 1.使用變量記錄函數 func demo() { let x:Int = sum(x: 20, y: 30) print("sum = \(x)") // 閉包: 提前准備好代碼,需要的時候執行,可以當做參數傳遞 // 定義一個常量記錄函數 (x: Int, y: Int) -> Int let f = sum // 在需要的時候執行 在OC是不能實現 print(f(x: 30, y: 30)) } func sum(x:Int,y: Int) -> Int { return x + y } }