Swift中闭包(closure)的使用

时间:2020-12-23 22:48:36
有关闭包的定义:      typealias colsureName=(ParamClass,ParamClass?)->Void; 定义方法使用闭包时:      func colsureTestMethod:(colsureName):colsure;
eg:
//定义回调闭包
typealiasonSuccess=(MKNetworkOperation,String)->Void;
typealiasonError=(NSError)->Void; //调用    privatefuncoperation_request(#urlstring:String,parmaDic:[String:String],httpMethod:String,onSucc:onSuccess,onErr:onError){
       
let op:MKNetworkOperation=MKNetworkOperation(URLString: urlstring, params: parmaDic, httpMethod: httpMethod);
        op.
addCompletionHandler({ (mop:MKNetworkOperation!) -> Void in
            onSucc(mop,mop.
responseString());
            }, errorHandler: { (mop:
MKNetworkOperation!, err:NSError!) -> Void in
                onErr(err);
        });
       
net_engine?.enqueueOperation(op);
    }

方法内直接定义colsure并且为参数的用法: funclogtrue(predicate:(Int,Int)->Int)->Bool{
   
var a = 100
   
var b = 101
   
return predicate(a,b)>a*b
} 输出结果:false
varflag = logtrue { (a:Int, c:Int) -> Int in
   
return a+c
}

关于@autoclosure  funclogbool(@autoclosurepredicate:()->Bool){
   
if predicate(){
       
print("true")
    }
else{
       
print("false")
    }
} @autoclosure 定义的闭包,可以直接使用类似logbool(2>1)” 的写法来使用 或者“ logbool({return2>1}())”的方法来使用,@autoclosure 只能用来定义无参数的闭包
funclogboolValue(predicate:()->Bool){
   
if predicate(){
       
print("true")
    }
else{
       
print("false")
    }
}
logboolValue({return2>1})