How to use Swift @autoclosure

后端 未结 6 1384
天命终不由人
天命终不由人 2020-12-02 04:44

I noticed when writing an assert in Swift that the first value is typed as

@autoclosure() -> Bool

with an overloaded method

6条回答
  •  时光取名叫无心
    2020-12-02 04:49

    @autoclosure is a function parameter which accept a cooked function(or returned type) meanwhile a general closure accept a raw function

    • @autoclosure argument type parameter must be '()'
      @autoclosure ()
      
    • @autoclosure accept any function with only appropriate returned type
    • Result of closure is calculated by demand

    Let's take a look at example

    func testClosures() {
    
        //closures
        XCTAssertEqual("fooWithClosure0 foo0", fooWithClosure0(p: foo0))
        XCTAssertEqual("fooWithClosure1 foo1 1", fooWithClosure1(p: foo1))
        XCTAssertEqual("fooWithClosure2 foo2 3", fooWithClosure2(p: foo2))
    
        XCTAssertEqual("fooWithClosure2 foo2 3", fooWithClosure2(p: { (i1, i2) -> String in
            return "fooWithClosure2 " + "foo2 " + String(i1 + i2)
        }))
    
        //@autoclosure
        XCTAssertEqual("fooWithAutoClosure HelloWorld", fooWithAutoClosure(a: "HelloWorld"))
    
        XCTAssertEqual("fooWithAutoClosure foo0", fooWithAutoClosure(a: foo0()))
        XCTAssertEqual("fooWithAutoClosure foo1 1", fooWithAutoClosure(a: foo1(i1: 1)))
        XCTAssertEqual("fooWithAutoClosure foo2 3", fooWithAutoClosure(a: foo2(i1: 1, i2: 2)))
    
    }
    
    //functions block
    func foo0() -> String {
        return "foo0"
    }
    
    func foo1(i1: Int) -> String {
        return "foo1 " + String(i1)
    }
    
    func foo2(i1: Int, i2: Int) -> String {
        return "foo2 " + String(i1 + i2)
    }
    
    //closures block
    func fooWithClosure0(p: () -> String) -> String {
        return "fooWithClosure0 " + p()
    }
    
    func fooWithClosure1(p: (Int) -> String) -> String {
        return "fooWithClosure1 " + p(1)
    }
    
    func fooWithClosure2(p: (Int, Int) -> String) -> String {
        return "fooWithClosure2 " + p(1, 2)
    }
    
    //@autoclosure
    func fooWithAutoClosure(a: @autoclosure () -> String) -> String {
        return "fooWithAutoClosure " + a()
    }
    

提交回复
热议问题