关闭和一等功能之间的差异?

前端之家收集整理的这篇文章主要介绍了关闭和一等功能之间的差异?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Swift文档中,Apple表示:

Closures are self-contained blocks of functionality that can be passed
around and used in your code. Closures in Swift are similar to blocks
in C and Objective-C and to lambdas in other programming languages.

我以为是First-class functions的定义

他们也说:

Closures can capture and store references to any constants and
variables from the context in which they are defined. This is known as
closing over those constants and variables. Swift handles all of the
memory management of capturing for you.

我认为这是封闭的定义,而另一个定义是一流的功能,但苹果似乎把它们放在一起,称之为关闭.

我有误解吗?或者是苹果关闭和一级功能关闭

我写了这个示例代码,只想知道我是否正确的书面评论

// 'a' takes a first class function,which makes 'a' a higher order function
func a(ch: () -> Void){
    print("Something")
    ch()                // 'ch' is a first class function
    print("Ended")
}

func closureFunc(){
    var num = 2
    a({
        // access to 'num' is possible by closures
        num = num*2
        print(num)
    })
}

closureFunc()
这些概念是正交的.他们不直接相关;它们是关于Swift功能的两个事实.

>功能是一流的.这意味着它们可以传递 – 分配为变量,作为参数传递给函数参数,并作为结果传递给函数.
>函数是闭包.这意味着,在定义的时候,它们捕获函数体内所指的环境,但是在函数体之外被声明.

这是一个例子(从游乐场):

func multiplierMaker(i:Int) -> (Int) -> (Int) {
    func multiplier(ii:Int) -> (Int) {
        return ii*i
    }
    return multiplier
}
let g = multiplierMaker(10)
g(2) // 20

想想功能乘数:

>乘数可以作为函数乘数Maker的结果返回,并分配给g,并且它有一个定义良好的类型(Int) – > (Int),是因为函数是一流的.
>当10被传递到multiplierMaker中时,由此产生的乘法器函数将其参数乘以10,即使分配给g并且稍后调用,这是因为函数是闭包.

(请注意,这与匿名函数无关,所有答案或语句导致您认为闭包与匿名函数有关是错误的,本示例中没有匿名函数,匿名函数是一个闭包,但只是因为所有功能都是关闭.)

原文链接:https://www.f2er.com/swift/318793.html

猜你在找的Swift相关文章