美文网首页
Swift4 闭包小结

Swift4 闭包小结

作者: jzhang | 来源:发表于2017-03-29 22:57 被阅读16次
    //: Playground - noun: a place where people can play
    
    //Swift 闭包
    //定义
    //无参数无返回值的闭包
    var completionCallback :(()->())?
    //无参数有返回值的闭包
    var completionHandler:(()->Int)?
    //有参数无返回值的闭包
    var finishCallBack :((Int) ->())?
    //有参数有返回值的闭包
    var successHandler :((Int) ->(Int))?
    
    //无参数无返回值的闭包
    completionCallback = { () in
        print("无参数无返回值的闭包执行了");
    };
    
    completionCallback!();
    
    //无参数有返回值的闭包
    completionHandler = { ()in
        print("闭包被调用了");
        return 20;
    };
    let a = completionHandler!();
    print(" a:\(a)")
    
    //有参数无返回值的闭包
    finishCallBack = { (a) in
        print("有参数无返回值的闭包 a:\(a)")
    };
    
    finishCallBack!(10);
    
    //有参数有返回值的闭包
    successHandler = {(a) ->(Int)in
        print("有参数有返回值 a:\(a)");
        return 10;
    };
    
    let result = successHandler!(20);
    print(result);
    
    // 闭包作为参数传递的情况
    func successFunction(success:@escaping (Int)->(Int)) -> () {
        
        successHandler = success;
        
        let result = success(10);
        
        print("successFunction result :::\(result)")
        
    }
    
    
    func doSomthing(finish:@escaping (Int)->()) -> () {
        
        finishCallBack = finish;
        
        finish(10);
        
        
    }
    
    func loadNetWorkData(completion:@escaping ()->Int) -> () {
        
        completionHandler = completion;
        
        let a = completion();
        
        print("a:\(a)");
        
        
    }
    
    

    相关文章

      网友评论

          本文标题:Swift4 闭包小结

          本文链接:https://www.haomeiwen.com/subject/zddyottx.html