初探swift語言的學習筆記十(block)

來源:互聯網
上載者:User

標籤:swift   iphone   object-c   block   閉包   

fengsh998原文地址:http://blog.csdn.net/fengsh998/article/details/35783341轉載請註明出處如果覺得文章對你有所協助,請通過留言或關注公眾帳號fengsh998來支援我,謝謝!


在前面一些學習中,原本把閉包給理解成了block儘管有很多相似之處,但block還是有他自己的獨特之外。近日,在寫oc/swift混合編碼時,有時候需要swift回調oc,oc回調swift 。

因此我把swift中的 block 常見的聲明和寫法作一個總結。以免後續忘了,好查閱。廢話不說多,上例子:

////  blockDemo.swift//  swiftDemo////  Created by apple on 14-6-29.//  Copyright (c) 2014年 fengsh. All rights reserved.//import Foundation//無參無傳回值typealias funcBlock = () -> () //或者 () -> Void//傳回值是Stringtypealias funcBlockA = (Int,Int) -> String//傳回值是一個函數指標,入參為Stringtypealias funcBlockB = (Int,Int) -> (String)->()//傳回值是一個函數指標,入參為String 傳回值也是Stringtypealias funcBlockC = (Int,Int) -> (String)->Stringclass blockDemo{    //block作為屬性變數    var blockProperty : (Int,Int) -> String = {a,b in return ""/**/} // 帶初始化方式    var blockPropertyNoReturn : (String) -> () = {param in }        var blockPropertyA : funcBlockA?  //這寫法就可以初始時為nil了,因為生命周其中,(理想狀態)可能為nil所以用?    var blockPropertyB : funcBlockB!  //這寫法也可以初始時為nil了,因為生命周其中,(理想狀態)認為不可能為nil,所以用!        init()    {        println("blockPropertyA = \(blockPropertyA) , blockPropertyB = \(blockPropertyB)")        println("blockProperty = \(blockProperty) , blockPropertyNoReturn = \(blockPropertyNoReturn)")    }        func testProperty(tag:Int)    {        switch (tag)        {        case 1:                self.blockPropertyNoReturn("OK GOOD")        case 2:                if let exsistBlock = self.blockPropertyA                {                    let result = self.blockPropertyA!(7,8)                    println("result = \(result)")                }        case 3:                if let exsistBlock = self.blockPropertyB                {                    let fc = self.blockPropertyB(1,2)                    fc("輸出")                }        default:                let ret = self.blockProperty(3,4)                println(ret)        }    }        //block作為函數參數    func testBlock(blockfunc:funcBlock!)//使用!號不需要再解包    {        if let exsistblock = blockfunc        {            blockfunc() //無參無返回        }    }        func testBlockA(blockfunc:funcBlockA!)    {        if let exsistblock = blockfunc        {            let retstr = blockfunc(5,6)            println(retstr)        }    }        func testBlockB(blockfunc:funcBlockB!)    {        if let exsistblock = blockfunc        {           let retfunc = blockfunc(5,6)            retfunc("結果是")        }    }        func testBlockC(blockfunc:funcBlockC!)    {        if let exsistblock = blockfunc        {            let retfunc = blockfunc(5,6)            let str = retfunc("最終果結是")            println(str)        }    }}

執行測試碼:

        var bk = blockDemo()        //block設定前,啥也沒有輸出        bk.testProperty(0)        bk.testProperty(1)        bk.testProperty(2)        bk.testProperty(3)        println("==============設定block屬性================")                bk.blockProperty = {            (a :Int,b:Int) -> String in            let c = a*100+b            return "\(a)*100+\(b) = \(c)"        }        bk.testProperty(0)                bk.blockPropertyNoReturn = {            (param:String) -> () in            println("input param value is : \(param)")        }        bk.testProperty(1)                bk.blockPropertyA = {            (a:Int,b:Int) -> String in            let c = a*100+b*200            return "\(a)*100+\(b)*200 = \(c)"        }        bk.testProperty(2)                bk.blockPropertyB = {            (a:Int,b:Int) -> (String)->() in            func sumprint(result:String)            {                let c = a + b;                println("sumprint func print:parame :\(result) \(a) + \(b) = \(c)")            }                        return sumprint        }        bk.testProperty(3)        println("==============屬性block完成================")        println("==============函數block為nil時無輸出================")        bk.testBlock(nil)        bk.testBlockA(nil)        bk.testBlockB(nil)        bk.testBlockC(nil)        println("==============函數block操作================")        bk.testBlock({                //do something                println("無參無傳回值block 執行")            })                bk.testBlockA({                (a:Int,b:Int) -> String in                let c = a*400+b*1000                return "\(a)*400 + \(b)*1000 is \(c)"            })                bk.testBlockB({            (a:Int,b:Int) -> (String)->() in            func sumprint(result:String)            {                let c = a / b;                println("sumprint func print:parame :\(result) \(a) / \(b) = \(c)")            }                        return sumprint            })                bk.testBlockC({            (a:Int,b:Int) -> (String)->String in                func sumrsult(res:String) -> String                {                    let c = a*a+b*a                    return "\(res) \(a)*\(a)+\(b)*\(a) = \(c)"                }                return sumrsult            })
以上包括了block聲明和使用
下面是輸出結果

blockPropertyA = nil , blockPropertyB = nilblockProperty = (Function) , blockPropertyNoReturn = (Function)==============設定block屬性================3*100+4 = 304input param value is : OK GOODresult = 7*100+8*200 = 2300sumprint func print:parame :輸出 1 + 2 = 3==============屬性block完成==============================函數block為nil時無輸出==============================函數block操作================無參無傳回值block 執行5*400 + 6*1000 is 8000sumprint func print:parame :結果是 5 / 6 = 0最終果結是 5*5+6*5 = 55

好了,我想這個比文字語方描述的更為清楚吧。如有不明白或其它奇怪寫法,歡迎踢館。。。。。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.