Swift Learning tip of the Day (5) @autoclosure

Source: Internet
Author: User

@autoclosure can be said to be one of Apple's most amazing creations.

Simply put, what @autoclosure do is to automatically encapsulate an expression into a closure (closure). This can sometimes look very beautiful in grammar.

For example, we have a way to accept a closure and print when the result of the closure execution is true:

func logIfTrue(predicate: () -> Bool) {    if predicate() {        println("True")    }}

At the time of the call, we need to write this code.

logIfTrue({return 2 > 1})

Of course, there are some simplifications to the use of closures in Swift, in which case we can omit the return and write:

logIfTrue({2 > 1})

It can be a step closer because the closure is the last parameter, so you can use the trailing closure (trailing closure) to take the curly brace out, and then omit the parentheses and turn it into:

logIfTrue{2 > 1}

But either way, it's hard to write, or it's not very clear, and it seems to be annoying. So @autoclosure appeared. We can change the method parameter and precede the parameter name with @autoclosure keyword:

func logIfTrue(@autoclosure predicate: () -> Bool) {    if predicate() {        println("True")    }}

Then we can write directly:

logIfTrue(2 > 1)

To make the call, Swift will be 2 > 1 the expression is automatically converted to ()-Bool. So we get a simple, ideographic formula.

最后要提一句的是,@autoclosure 并不支持带有输入参数的写法,也就是说只有形如 () -> T 的参数才能使用这个特性进行简化。另外因为调用者往往很容易忽视 @autoclosure 这个特性,所以在写接受 @autoclosure 的方法时还请特别小心,如果在容易产生歧义或者误解的时候,还是使用完整的闭包写法会比较好。

Swift Learning tip of the Day (5) @autoclosure

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.