-->

How to comprehend the “first-class function” in sw

2020-05-08 18:00发布

问题:

I am reading some books about the functional programming in swift. When I see some books said the function in swift is "first-class function" and I confused what is the meaning of the "first-class". Can anybody answer me or give me some example code?

回答1:

Functions are first-class citizens in Swift because you can treat a function like a normal value. For example, you can …

  • assign a function to a local variable,
  • pass a function as an argument to another function, and
  • return a function from a function.


回答2:

Its just fancy terminology that is currently trendy. It just means that you can have a variable that holds a reference to a function.

Its been in programming forever; in C and Fortran you have pointers to functions. Typical use in both these languages is to pass a compare function into a sort function so that the sort function can sort any data type.

In some languages, e.g. Java, it appears that you don't have pointers to functions, but you do have pointers to interfaces. So you define a Comparable interface with a compare method and pass an instance of Comparable to your sort.

Nothing new, just confusing terminology for a familiar concept. Presumably to try and make the feature sound new and sexy.



回答3:

Please see my answer in this question. And I will add one more example (please check the example in that question first):

func operateMono( operand: String) -> (Double -> Double)?{
    switch operand{
    case "log10":
        return log
    case "log2":
        return log2
    case "sin":
        return sin
    case "cos":
        return cos
    default:
        return nil
    }
}

And the usage

var functionMono = operateMono("log10")
print ("log10 for 10 = \(functionMono!(10))")

functionMono = operateMono("log2")
print ("log2 for 10 = \(functionMono!(10))")

functionMono = operateMono("sin")
print ("sin 10 = \(functionMono!(10))")

functionMono = operateMono("cos")
print ("cos 10 = \(functionMono!(10))")