Swift开发

Swift 闭包

2017-11-27  本文已影响2人  追逐_chase
Swift.png
闭包
//闭包
var add:(Int,Int) ->(Int) = {
    
    (a,b) ->(Int) in
    
    print(a + b);
    return a + b;
}

add(10,20);

// { (a:Int,b:Int)  in   return: 10}     => (Int,Int) ->(Int)

//小例子


//闭包
var sub:(_ a:Int,_ b:Int) ->(Int) = {
    
    (a:Int, b:Int) -> (Int) in
    
    print(a - b);
    
    return a - b;
}

sub(30, 10);



func hanshu(n1:Int,n2:Int,block:(Int,Int) ->(Int)) -> Int {
    
    return block(n1, n2);
}

//调用的第一种形式  sub是一个 闭包
hanshu(n1: 10, n2: 3, block: sub);

//第二种形式


hanshu(n1: 10, n2: 3, block: {
    
    (a:Int, b:Int) -> (Int) in
    
    print(a - b);
    
    return a - b;
});


// 打印结果是:7

参数闭包
var add:(Int, Int) ->(Int) = {
    (a:Int,b:Int) -> (Int) in
    
    print( a + b);
    
    return a + b;
}

func test(a:Int, b:Int, Block:(Int,Int) ->(Int)) ->Int {
    
    print("闭包作为参数");
    
    return 10;
}


test(a: 10, b: 10, Block: add);

// 闭包

func test(Block:(Int,Int) ->(Int)) {
    
    
    print("测试闭包");
}


//调用函数   {} 代表闭包, a和b是int型的参数
test { (a, b) -> (Int) in
    
    return a + b;
}


逃逸闭包

//逃逸闭包

func test(Block:@escaping (Int,Int) ->(Int)) {
    
    //创建一个队列
    let queue = DispatchQueue(label: "bibao");
    let time = DispatchTime.now() + DispatchTimeInterval.seconds(2);
    queue.asyncAfter(deadline: time, execute: {
        
       let result =  Block(2, 3);
        print(result);
        
    });
 
}

test { (a, b) -> (Int) in
    
    return a + b;
}

闭包循环引用问题
class Person {
    
    //闭包  可选类型
    var resultBlock:(() ->())?
    
    var name:String?
    
    
    func test() {
        //赋值
        //方式一
      weak var weakSelf = self;
     
        resultBlock = {
            print("看看",weakSelf);
        }
        
        //调用  要解析
        resultBlock?();
        
    }
    
    deinit {
        
        print("释放");
    }
}

var p:Person? = Person();

p?.test();

p = nil;

class Person {
    
    //闭包  可选类型
    var resultBlock:(() ->())?
    
    var name:String?
    
    
    func test() {
        //赋值
        resultBlock = {
              //方式二
              [weak self] in
            print("看看",weakSelf);
        }
        
        //调用  要解析
        resultBlock?();
        
    }
    
    deinit {
        
        print("释放");
    }
}
var p:Person? = Person();

p?.test();

p = nil;



上一篇下一篇

猜你喜欢

热点阅读