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

后端 未结 5 1291
北海茫月
北海茫月 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:23

    First-Class functions are functions that can return another functions. For instance:

    func operate( operand: String) -> ((Double, Double) -> Double)?{
    
        func add(a: Double, b: Double) -> Double {
            return a + b
        }
    
        func min(a: Double, b: Double) -> Double{
            return a - b
        }
    
        func multi(a: Double, b: Double) -> Double {
            return a * b
        }
    
        func div (a: Double, b: Double) -> Double{
            return a / b
        }
    
        switch operand{
        case "+":
            return add
        case "-":
            return min
        case "*":
            return multi
        case "/":
            return div
        default:
            return nil
        }
    }
    

    The function operate returns a function that takes two double as its arguments and returns one double.

    The usage of this function is:

    var function = operate("+")
    print(" 3 + 4 = \(function!(3,4))")
    
    function = operate("-")
    print(" 3 - 4 = \(function!(3,4))")
    
    function = operate("*")
    print(" 3 * 4 = \(function!(3,4))")
    
    function = operate("/")
    print(" 3 / 4 = \(function!(3,4))")
    

    When you don't care about the implementation of a function, using First-Class functions to return these functions become beneficials. Plus, sometimes, you are not responsible to develop (or not authorised ) of the functions like add, min. So someone would develop a First-Class function to you that returns these functions and it is your responsibility to continue ....

提交回复
热议问题