Swift - 6.3 逃逸闭包和自动闭包

2023-02-17  本文已影响0人  村雨灬龑

逃逸闭包

    var completionHandlers: [() -> Void] = []
    // @escaping () -> Void 是个逃逸闭包, 因为将闭包添加到外部变量数组中,并没有调用这个闭包, 而是知道数组completionHandlers[] 被调用的时候,运行数组中的闭包时闭包才会调用,这就是逃逸闭包
    func comeFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
        completionHandlers.append(completionHandler)
    }

    // 全局函数
    func comeFunctionWithNoEscapingClosure(closure: () -> Void) {
        closure()
    }

    class SomeClass {
        var x = 10
        func doSomething() {
            comeFunctionWithEscapingClosure {
                self.x = 100
            }
            comeFunctionWithNoEscapingClosure {
                x = 200
            }
        }
    }

    let instance = SomeClass()
    instance.doSomething()
    // print 200,表示着调用了全局函数 comeFunctionWithNoEscapingClosure,而 comeFunctionWithEscapingClosure 逃逸闭包函数没有被调用,闭包已逃逸了
    print(instance.x)

    // comeFunctionWithEscapingClosure 中的闭包已经逃逸到数组中了, 只有在调用数组中的闭包时,才会重新给x赋值,所以现在的x 的值 是 100
    completionHandlers.first?()
    print(instance.x)

自动闭包

    var customersInLines = ["张三", "赵云", "安其拉", "邓紫棋"]
    print(customersInLines.count) // print: 4

    // 只是创建了闭包,但是没有调用,只有调用该闭包的时候,才会实现闭包内部的方法
    let customerProvider = { customersInLines.remove(at: 0)}
    print(customersInLines.count) // print: 4

    print("Now serving \(customerProvider())!")
    print(customersInLines.count) // print: 3
    var customersInLines = ["张三", "赵云", "安其拉", "邓紫棋"]

    func serve(customer customerProvider: () -> String) {
        print("Now serving \(customerProvider())!")
    }

    serve(customer: { customersInLines.remove(at: 0)})
    var customersInLines = ["张三", "赵云", "安其拉", "邓紫棋"]

    func serve(customer customerProvider: @autoclosure () -> String) {
        print("Now serving \(customerProvider())!")
    }

    // 使用 @autoclosure 标签, 传入的实际参数可以不使用{},也不是一个闭包了,传入后会自动转换成闭包
    serve(customer: customersInLines.remove(at: 0))

自动 + 逃逸闭包

    var customerProviders: [() -> String] = []
    var customersInLines = ["张三", "赵云", "安其拉", "邓紫棋"]

    func collectCustomerProvider(customerProvider: @autoclosure @escaping () -> String) {
        customerProviders.append(customerProvider)
    }

    collectCustomerProvider(customerProvider: customersInLines.remove(at: 0))
    collectCustomerProvider(customerProvider: customersInLines.remove(at: 0))

    print("Collected \(customerProviders.count) closures.")

    for customerProvider in customerProviders {
        print("Now serving \(customerProvider())!")
    }
上一篇 下一篇

猜你喜欢

热点阅读