19.Swift中的閉包

import UIKit


class HttpTool: NSObject {

    

    var callBack : (()->())?

    

    /*

    閉包的寫法:

    類型:(參數列表) -> (返回值)

    

    建議:寫閉包時,記住格式直接先寫 () -> ()

        在需要參數或者返回值,在內部填充對應的東西即可

    */

    

    func loadData(callBack : () -> ()) {

        self.callBack = callBack

        

        dispatch_async(dispatch_get_global_queue(0, 0)) {

            print("網絡請求數據:", NSThread.currentThread())

            

            dispatch_async(dispatch_get_main_queue(), {

                callBack()

            })

        }

    }

}



import UIKit


class ViewController: UIViewController {

    

    // 使用類時不需要導入類,默認自己創建的類在同一個命名空間中

    var httpTool : HttpTool = HttpTool()


    override func viewDidLoad() {

        super.viewDidLoad()

    }

    

    func btnClick() {

        print("btnClick")

    }

    

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        

        // 閉包的常規寫法

//        httpTool.loadData { () -> () in

//            print("加載數據完成,更新界面:", NSThread.currentThread())

//        }

        

        // 閉包的簡寫:如果閉包是沒有參數,並且沒有返回值,那麼閉包中 () -> () in 可以省略

        // 開發中建議該寫法

        

        // 解決方案一:

//        weak var weakSelf = self

//        

//        httpTool.loadData {

//            print("加載數據完成,更新界面:", NSThread.currentThread())

//            weakSelf!.view.backgroundColor = UIColor.redColor()

//        }

        

        // 解決方案二:

        // weak var weakSelf = self

        

//        httpTool.loadData {[weak self] () -> () in

//            print("加載數據完成,更新界面:", NSThread.currentThread())

//            self!.view.backgroundColor = UIColor.redColor()

//        }

        

        // 解決方案三:

        // unowned關鍵字相當於__unsafe_unretained,指向一個內存地址,不管該對象是否被銷燬.依然指向該內存地址

        httpTool.loadData {[unowned self] () -> () in

            print("加載數據完成,更新界面:", NSThread.currentThread())

            self.view.backgroundColor = UIColor.redColor()

        }

    }

    

    // 析構函數(相當於OCdealloc方法)

    deinit {

        print("ViewController----deinit")

    }

}



第二: 閉包簡介

/*

閉包:

函數是閉包的一種

類似於OC語言的block

閉包表達式(匿名函數) -- 能夠捕獲上下文中的值


語法: in關鍵字的目的是便於區分返回值和執行語句

閉包表達式的類型和函數的類型一樣, 是參數加上返回值, 也就是in之前的部分

{

    (參數) -> 返回值類型 in

    執行語句

}

*/



// 完整寫法

let say:(String) -> Void = {

    (name: String) -> Void in

    print("hi \(name)")

}

say("lnj")



// 沒有返回值寫法

let say2:(String) ->Void = {

    (name: String) in

    print("hi \(name)")

}

say2("lnj")



// 沒有參數沒有返回值寫法

let say3:() ->Void = {

    print("hi lnj")

}

say3()



/*

閉包表達式作爲回調函數

*/

func showArray(array:[Int])

{

    for number in array

    {

        print("\(number), ")

    }

}

/*

// 缺點, 不一定是小到大, 不一定是全部比較, 有可能只比較個位數

// 所以, 如何比較可以交給調用者決定

func bubbleSort(inout array:[Int])

{

    let count = array.count;

    for var i = 1; i < count; i++

    {

        for var j = 0; j < (count - i); j++

        {

            if array[j] > array[j + 1]

            {

                let temp = array[j]

                array[j] = array[j + 1]

                array[j + 1] = temp

            }

        }

    }

}

*/


let cmp = {

    (a: Int, b: Int) -> Int in

    if a > b{

        return 1;

    }else if a < b

    {

        return -1;

    }else

    {

        return 0;

    }

}


func bubbleSort(inout array:[Int], cmp: (Int, Int) -> Int)

{

    let count = array.count;

    for var i = 1; i < count; i++

    {

        for var j = 0; j < (count - i); j++

        {

            if cmp(array[j], array[j + 1]) == -1

            {

                let temp = array[j]

                array[j] = array[j + 1]

                array[j + 1] = temp

            }

        }

    }

}


var arr:Array<Int> = [31, 13, 52, 84, 5]

bubbleSort(&arr, cmp: cmp)

showArray(arr)



// 閉包作爲參數傳遞

bubbleSort(&arr, cmp: {

    (a: Int, b: Int) -> Int in

    if a > b{

        return 1;

    }else if a < b

    {

        return -1;

    }else

    {

        return 0;

    }

})

print("---------------")

showArray(arr)



// 如果閉包是最後一個參數, 可以直接將閉包寫到參數列表後面, 這樣可以提高閱讀性. 稱之爲尾隨閉包

bubbleSort(&arr) {

    (a: Int, b: Int) -> Int in

    if a > b{

        return 1;

    }else if a < b

    {

        return -1;

    }else

    {

        return 0;

    }

}



// 閉包表達式優化,

// 1.類型優化, 由於函數中已經聲明瞭閉包參數的類型, 所以傳入的實參可以不用寫類型

// 2.返回值優化, 同理由於函數中已經聲明瞭閉包的返回值類型,所以傳入的實參可以不用寫類型

// 3.參數優化, swift可以使用$索引的方式來訪問閉包的參數, 默認從0開始

bubbleSort(&arr){

//    (a , b) -> Int in

//    (a , b) in

    if $0 > $1{

        return 1;

    }else if $0 < $1

    {

        return -1;

    }else

    {

        return 0;

    }

}



// 如果只有一條語句可以省略return

let hehe = {

    "我是lnj"

}

print(hehe())


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章