Swift的函數與函數指標、閉包Closure等相關內容介紹

來源:互聯網
上載者:User

標籤:

<span style="font-size:24px;">//函數//demo1 無參數類型func testConcat(){    println("測試函數");}testConcat()//調用demo1//demo2 多參數,一個傳回值/*    函數以func開頭,表示一個函數    v1表示參數,String參數類型    ->傳回值類型String*/func testConcats(v1:String,v2:String) ->String{    return "\(v1) and \(v2)";}//函數參數含有標籤func testConcatAndMark(v1:String,AndValue v2:String,AndNumber v3:String)->String{        return "\(v1),\(v2),\(v3)"}//測試函數func testFunction(){    let v = testConcats("hello", "world");    println(v);    let v2 = testConcatAndMark("david", AndValue: "dream", AndNumber: "good");    println(v2)}testFunction();//函數返回多值func getInfo()->(String,String,Int){    return ("david","dream",100);}let (v1,v2,v3)=getInfo();println("v1=\(v1),v2=\(v2),v3=\(v3)");//函數嵌套函數func testFunctionInFunction()->Int{    var y = 10;    func add(){        y+=5;    }    add();    return y;}let v6 = testFunctionInFunction();//*******************************//函數指標 *****五星難度/*    傳回值是(Int->Int),是個函數地址    第一個int是參數類型,第二個int是傳回值*/func getFuncPointer()->(Int->Int) {    func addOne(num:Int)->Int{        return num+1;    }    return addOne;//返回一個函數 地址}var funPointer = getFuncPointer();//funPointer是個函數指標var v7 = funPointer(100);//函數的形式調用func get()->(Int->String){    func post(count:Int)->String{        if count>50{            return "success";        }else{            return "failed"        }    }    return post;}let v8 = get();//v8拿到的是get()函數的地址let v9 = v8(58);//v9拿到的是get函數的傳回值//函數指標/地址作為參數,函數作為參數傳給函數,函數的傳遞</span>
<span style="font-size:24px;"></span>
<span style="font-size:24px;">//閉包是痛點,閉包的作用主要是函數與函數之間的溝通,有點像Block</span>
<span style="font-size:24px;"></span><pre name="code" class="objc">//(num:Int)->Bool閉包參數類型func hasColsureMatch(arr:Int[],value:Int,cb:(num:Int)->Bool){    for item in arr{        if cb(item){            return true;        }    }    return false;}var ar = [20,9.100,34,89,39];var v1 = hasClosureMatch(arr,40,{    (num:Int) -> Bool in    return num >= 40;});println("v1 is \(v1)");




Swift的函數與函數指標、閉包Closure等相關內容介紹

相關文章

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.