资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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, 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()

        }

    }

    

   // 析构函数(相当于OC中dealloc方法)

    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 = [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())


新闻标题:19.Swift中的闭包
文章分享:http://cdkjz.cn/article/jgehgj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220