“Functions are a first-class type” in swift?

后端 未结 5 1298
北海茫月
北海茫月 2021-02-03 13:21

the little knowledge , I have about first class function is that it supports passing functions as arguments and we can also return them as the values in another function ... I a

5条回答
  •  暖寄归人
    2021-02-03 14:26

    Any programming language is said to have first-class-functions, when functions are treated like normal variables. That means a function can be passed as parameter to any other function, can be returned by any function and also can be assigned to any variable.

    i.e., (Referring apple's examples)

    Passing function as parameter

    func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
        for item in list {
            if condition(item) {
                return true
            }
        }
        return false
    }
    

    Returning function

    func makeIncrementer() -> ((Int) -> Int) {
        func addOne(number: Int) -> Int {
            return 1 + number
        }
        return addOne
    }
    

提交回复
热议问题